二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)

每个 LED 代表一个 0 或 1,最低位在右侧。

LeetCode 401. 二进制手表(C++、python)

例如,上面的二进制手表读取 “3:25”。

给定一个非负整数 代表当前 LED 亮着的数量,返回所有可能的时间。

案例:

输入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

 

注意事项:

输出的顺序没有要求。

小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。

分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。

C++

class Solution {
public:
    int com(int a)
    {
        int count=0;
        while(a)
        {
            if(1==a%2)
            {
                count++;
            }
            a/=2;
        }
        return count;
    }
    
    vector<string> readBinaryWatch(int num) 
    {
        vector<string> res;
        for(int i=0;i<=11;i++)
        {
            for(int j=0;j<=59;j++)
            {
                if(com(i)+com(j)==num)
                {
                    if(j<10)
                    {
                        string tmp=to_string(i)+":0"+to_string(j);
                        res.push_back(tmp);
                    }
                    else
                    {
                        string tmp=to_string(i)+":"+to_string(j);
                        res.push_back(tmp);
                    }
                }
            }
        }
        return res;
    }
};

python

class Solution:
    def readBinaryWatch(self, num: int) -> List[str]:
        res=[]
        for i in range(12):
            for j in range(60):
                k=bin(i).count('1')+bin(j).count('1')
                if k==num:
                    if j<10:
                        s=str(i)+":0"+str(j)
                    else:
                        s=str(i)+":"+str(j)
                    res.append(s)
        return res
        

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-31
  • 2021-10-06
  • 2021-09-24
  • 2021-12-04
  • 2021-08-26
猜你喜欢
  • 2021-09-04
  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
  • 2021-05-30
相关资源
相似解决方案