[LeetCode] Binary Watch

401. Binary Watch

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

  • For example, the below binary watch reads “4:51”.

Given an integer turnedOn which represents the number of LEDs that are currently on, return all possible times the watch could represent. You may return the answer in any order.

The hour must not contain a leading zero.

  • For example, “01:00” is not valid. It should be “1:00”.

The minute must be consist of two digits and may contain a leading zero.

  • For example, “10:2” is not valid. It should be “10:02”.
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
class Solution {
vector<string> res;
int convert(string binary) {
int res = 0;
for(int i = binary.length() - 1, bit = 1; i >= 0; i--, bit *= 2) {
if(binary[i] == '1') res += bit;
}
return res;
}
vector<pair<int, int>> helper(int bi) {
string time = string(10 - bi, '0') + string(bi, '1');
vector<pair<int, int>> res;
do {
string h = time.substr(0, 4);
string m = time.substr(4);
res.push_back({convert(h), convert(m)});
}while(next_permutation(begin(time), end(time)));
return res;
}
public:
vector<string> readBinaryWatch(int turnedOn) {
auto am = helper(turnedOn);
for(auto& [t, m] : am) {
if(t >= 12 or m >= 60) continue;
res.push_back(to_string(t) + ":" + (m < 10 ? "0" + to_string(m) : to_string(m)));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/29/PS/LeetCode/binary-watch/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.