二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。
给定一个非负整数 n 代表当前 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”。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-watch
方法:这道题是简单题,但是一开始想用回溯的方法,但是一时想不到好的方法,于是去官网题解看了一下参考别人的方法,然后测试还达到100%。
主要思想就是看所有可能时间里面二进制1的个数。用了一个按位与,这是一个新的知识点。
class Solution {
public:
vector<string> readBinaryWatch(int num) {
for(int i = 0; i < 12; i++){
if(count1(i) == num) res.push_back( to_string(i) + ":00");
else{
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;
}
private:
vector<string> res;
//统计二进制1的个数
int count1(int nums){
int c1 = 0;
while(nums != 0){
nums = nums & (nums - 1); //按位与
c1++;
}
return c1;
}
};
方法2:回溯法,后续有时间补充。