forked from jhflorey/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryWatch.cpp
executable file
·62 lines (59 loc) · 1.47 KB
/
BinaryWatch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
*
* Tag: Hash & Bit Manipulation
* Time: O(1)
* Space: O(1)
*/
class Solution {
public:
vector<string> readBinaryWatch(int num) {
init();
vector<string> ans;
unordered_set<string>::iterator hidx, midx;
string h = "", m = "";
for(int i = 0; i <= num; ++ i){
if(hh.find(i) == hh.end() || mm.find(num - i) == mm.end())
continue;
for(hidx = hh[i].begin(); hidx != hh[i].end(); ++ hidx){
h = *hidx;
for(midx = mm[num - i].begin(); midx != mm[num - i].end(); ++ midx){
m = *midx;
ans.push_back(h+":"+m);
}
}
}
return ans;
}
private:
void init(){
hh.clear();
mm.clear();
int cnt = 0, v = 0;
string str_v = "";
for(int i = 0; i < 12; ++ i){
cnt = 0;
v = i;
while(v){
if(v&1)
++ cnt;
v >>= 1;
}
hh[cnt].insert(to_string(i));
}
for(int i = 0; i < 60; ++ i){
cnt = 0;
v = i;
while(v){
if(v&1)
++ cnt;
v >>= 1;
}
str_v = to_string(i);
if(i < 10)
str_v = "0"+str_v;
mm[cnt].insert(str_v);
}
}
private:
unordered_map<int, unordered_set<string>> hh, mm;
};