-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathBinary Watch.cpp
101 lines (77 loc) · 2.12 KB
/
Binary Watch.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class Solution {
public:
string convertCombination(int *c, int k)
{
int hours=0;
int minutes=0;
for(int i=0;i<k;i++)
{
int indicatorIdx = c[i];
switch(indicatorIdx)
{
case 0:
hours+=8;
break;
case 1:
hours +=4;
break;
case 2:
hours +=2;
break;
case 3:
hours +=1;
break;
case 4:
minutes += 32;
break;
case 5:
minutes += 16;
break;
case 6:
minutes += 8;
break;
case 7:
minutes += 4;
break;
case 8:
minutes += 2;
break;
case 9:
minutes += 1;
break;
}
}
if(hours>11 || minutes > 59) return ""; // invalid time
return (to_string(hours)+":"+to_string(minutes/10)+to_string(minutes%10));
}
vector<string> readBinaryWatch(int turnedOn) {
vector<string>result;
int k = turnedOn;
int c[10];
std::iota(begin(c),begin(c)+k,0);
constexpr int N = 10;
int count = 0;
string str = convertCombination(c, k);
if(!str.empty()) result.push_back(str);
// print(c,k,str);
while(true)
{
// go to the next combination
int alter_idx = 0; // count from the right digit
while(alter_idx<k && c[k-alter_idx-1]==(N-1-alter_idx)) alter_idx++;
if(alter_idx == k) break;
c[k-alter_idx-1]++;
for(int i=0;i<alter_idx;i++) c[k-alter_idx+i]=c[k-alter_idx-1]+1+i;
str = convertCombination(c, k);
if(!str.empty()) result.push_back(str);
// print(c,k,str);
}
return result;
}
void print(int *c, int k, string s)
{
if(s.empty()) return;
for(int i=0;i<k;i++) cout << c[i];
cout << " : " << s << endl;
}
};