-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathBinaryWatch.cpp
75 lines (66 loc) · 2.06 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
63
64
65
66
67
68
69
70
71
72
73
74
75
// Problem: https://leetcode.com/problems/binary-watch/
#include <string>
#include <vector>
using namespace std;
struct Time {
Time() : hours(0), minutes(0) {}
int hours;
int minutes;
};
class BinaryWatch {
public:
vector<string> readBinaryWatch(int turnedOn) {
if (turnedOn == 0) return {"0:00"};
// The first four digits are hours, and the next six are minutes.
vector<bool> digits;
digits.resize(10, 0);
// Encapsulates all the results in this vector.
vector<string> results;
// Iteration to get the next vector.
getNext(digits, 0, turnedOn, results);
sort(results.begin(), results.end());
// Return all the results.
return results;
}
private:
void getNext(vector<bool>& digits, int index, int turnedOn, vector<string>& results) {
if (turnedOn <= 0) return;
if (index >= 10) return;
Time time;
digits[index] = true;
if (turnedOn == 1) {
time = getTime(digits);
if (isValid(time)) results.push_back(toString(time));
} else {
getNext(digits, index + 1, turnedOn - 1, results);
}
digits[index] = false;
getNext(digits, index + 1, turnedOn, results);
}
Time getTime(vector<bool>& digits) {
Time t;
for (int i = 0; i < 4; ++i) {
if (digits[i]) t.hours += pow(2, 3 - i);
}
for (int i = 4; i < 10; ++i) {
if (digits[i]) t.minutes += pow(2, 9 - i);
}
return t;
}
bool isValid(const Time& t) {
if (t.minutes == 0 && t.hours == 0) return false;
return t.hours < 12 && t.minutes <= 59;
}
string toString(const Time& t) {
string time;
// Adding hours.
if (t.hours > 0) time = to_string(t.hours);
else time = "0";
// Adding separator.
time += ":";
// Adding minutes.
if (t.minutes >= 0 && t.minutes < 10) time += "0" + to_string(t.minutes);
else time += to_string(t.minutes);
return time;
}
};