mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2026-09-03 22:38:04 +08:00
add 401
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user