mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
33 lines
889 B
Markdown
33 lines
889 B
Markdown
![]() |
# [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;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|