A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to 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 (ignoring the PM), 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 consist of two digits and may contain a leading zero.
For example, "10:2" is not valid. It should be "10:02".
We know that all the numbers in binary watch have only 1 bit set. For eg. take the value 4 it is represented as 1000. Similarly, take the value 2, it is just 10. turnedOn in total should be equal to number of bits which can be set.
Then the idea is simple - iterate on hours and seconds - collect those times with correct number of 1 bits. For eg. when turnedOn = 1, we know that
classSolution {
public: vector<string> readBinaryWatch(int turnedOn) {
vector<string> ans;
for (int i =0; i <12; ++i) {
for (int j =0; j <60; ++j) {
if (__builtin_popcount(i) + __builtin_popcount(j) == turnedOn) {
ans.push_back(to_string(i) +":"+ (j <10?"0":"") + to_string(j));
}
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
funcreadBinaryWatch(turnedOnint) []string {
varans []stringfori:=0; i < 12; i++ {
forj:=0; j < 60; j++ {
ifbits.OnesCount(uint(i))+bits.OnesCount(uint(j)) ==turnedOn {
ans = append(ans, fmt.Sprintf("%d:%02d", i, j))
}
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
public List<String>readBinaryWatch(int turnedOn) {
List<String> ans =new ArrayList<>();
for (int i = 0; i < 12; ++i) {
for (int j = 0; j < 60; ++j) {
if (Integer.bitCount(i) + Integer.bitCount(j) == turnedOn) {
ans.add(String.format("%d:%02d", i, j));
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution:
defreadBinaryWatch(self, turnedOn: int) -> List[str]:
return [
'{:d}:{:02d}'.format(i, j)
for i in range(12)
for j in range(60)
if (bin(i) + bin(j)).count('1') == turnedOn
]