Skip to content

Commit dc201e6

Browse files
authored
Create binary-watch.cpp
1 parent 67f5f7f commit dc201e6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

C++/binary-watch.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<string> readBinaryWatch(int num) {
7+
vector<string> result;
8+
for (int h = 0; h < 12; ++h) {
9+
for (int m = 0; m < 60; ++m) {
10+
if (bit_count(h) + bit_count(m) == num) {
11+
const auto hour = to_string(h);
12+
const auto minute = m < 10 ? "0" + to_string(m) : to_string(m);
13+
result.emplace_back(hour + ":" + minute);
14+
}
15+
}
16+
}
17+
return result;
18+
}
19+
20+
private:
21+
int bit_count(int bits) {
22+
int count = 0;
23+
for (; bits; bits &= bits - 1) {
24+
++count;
25+
}
26+
return count;
27+
}
28+
};

0 commit comments

Comments
 (0)