二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。
例如,上面的二进制手表读取 “3:25”。
给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。
案例:
输入: n = 1
返回: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-watch
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
——————
解题思路:遍历每个时间,统计每个时间中1的个数是否和n的值一样,如果和n的值一样,则存到容器中。
class Solution {
public:
vector<string> readBinaryWatch(int num)
{
vector<string> res;
for (int i = 0; i < 12; i++)
{
for (int j = 0; j < 60; j++)
{
if (count1(i) + count1(j) == num)
{
res.push_back(to_string(i)+":"+(j < 10 ? "0"+to_string(j) : to_string(j)));
}
}
}
return res;
}
int count1(int n) # 该函数用于统计每一个时间中1的个数
{
int res = 0;
while (n != 0)
{
res += n % 2; # 如果n的余数为1,则res的值加1,然后将n/2
n = n/2;
}
return res;
}
};