LeetCode/solutions/401. Binary Watch.md
2022-11-22 23:04:43 +08:00

33 lines
889 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [401. Binary Watch](https://leetcode.cn/problems/binary-watch/)
# 思路
由于分钟和小时都是有限且很小的所以我们可以遍历一遍所有分钟检查其二进制表示中1的个数即可。是个简单题不要考虑太复杂。
# C++
```C++
class Solution {
private:
int bitCount(int num){
int res = 0;
while(num > 0){
res += (num % 2);
num /= 2;
}
return res;
}
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string>res;
for(int i = 0; i < 12; i++){
for(int j = 0; j < 60; j++){
if(bitCount(i) + bitCount(j) == turnedOn){
res.push_back(
to_string(i) + (j < 10 ? ":0" : ":") + to_string(j)
);
}
}
}
return res;
}
};
```