Binary Watch LeetCode solution in C++

1
class Solution {
2
public:
3
string convertCombination(int *c, int k) {
4
int hours = 0;
5
int minutes = 0;
6

7
for (int i = 0; i < k; i++) {
8
int indicatorIdx = c[i];
9
switch (indicatorIdx) {
10
case 0:
11
hours += 8;
12
break;
13

14
case 1:
15
hours += 4;
16
break;
17

18
case 2:
19
hours += 2;
20

21
break;
22

23
case 3:
24
hours += 1;
25

26
break;
27

28
case 4:
29
minutes += 32;
30
break;
31

32
case 5:
33
minutes += 16;
34

35
break;
36
case 6:
37
minutes += 8;
38

39
break;
40
case 7:
41
minutes += 4;
42

43
break;
44
case 8:
45
minutes += 2;
46

47
break;
48
case 9:
49
minutes += 1;
50

51
break;
52
}
53
}
54
if (hours > 11 || minutes > 59) return ""; // invalid time
55
return (to_string(hours) + ":" + to_string(minutes / 10) + to_string(minutes % 10));
56
}
57

58
vector<string> readBinaryWatch(int turnedOn) {
59
vector<string> result;
60

61
int k = turnedOn;
62

63
int c[10];
64
std::iota(begin(c), begin(c) + k, 0);
65

66
constexpr int N = 10;
67

68
int count = 0;
69
string str = convertCombination(c, k);
70
if (!str.empty()) result.push_back(str);
71
// print(c,k,str);
72
while (true) {
73
// go to the next combination
74
int alter_idx = 0; // count from the right digit
75
while (alter_idx < k && c[k - alter_idx - 1] == (N - 1 - alter_idx)) alter_idx++;
76
if (alter_idx == k) break;
77
c[k - alter_idx - 1]++;
78
for (int i = 0; i < alter_idx; i++) c[k - alter_idx + i] = c[k - alter_idx - 1] + 1 + i;
79
str = convertCombination(c, k);
80
if (!str.empty()) result.push_back(str);
81
// print(c,k,str);
82
}
83
return result;
84
}
85

86
void print(int *c, int k, string s) {
87
if (s.empty()) return;
88
for (int i = 0; i < k; i++) cout << c[i];
89
cout << " : " << s << endl;
90
}
91
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0