1,题目要求
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
2,题目思路
仔细对表盘进行观察,即为二进制的形式。由题目可知,小时的范围为0-11,分钟的范围为0-59,因此进行小时和分钟的遍历即可,看其二进制形式下的1的个数的和是否为给定的num:如果是则对其进行记录,不是则查看下一个时间。
例如图片中的时间为3点,1和2为亮灯的,而3的二进制形式为11,与二进制表盘完全对应。
这里利用到了c++中的一个方法:bitset,用于存储二进制位。
bitset就像一个bool类型的数组一样,但是有空间优化——bitset中的一个元素一般只占1 bit,相当于一个char元素所占空间的八分之一。
另外,c++中将数字转化为字符串需要用到to_string方法。
3,程序源码
#include<algorithm>
#include<iostream>
#include<vector>
#include<bitset>
using namespace std;
class Solution {
public:
vector<string> readBinaryWatch(int num) {
vector<string> res;
for(int hour = 0;hour < 12;hour++)
{
for(int mini = 0;mini < 60;mini++)
{
if((bitset<10>(hour).count()+bitset<10>(mini).count())==num)
{
res.push_back((to_string(hour) + (mini < 10?":0" : ":")) + to_string(mini));
}
}
}
return res;
}
};
int main()
{
Solution sol;
vector<string> result = sol.readBinaryWatch(1);
for (int i=0;i<result.size();i++)
cout<<result[i]<<endl;
return 0;
}