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.
Given a non-negative 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 (0-11) and minute (0-59) should be represented as a digital clock time of “HH:MM”.
Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
turnedOn
always valid such that 0 <= turnedOn
<= 10?
turnedOn
will always be within this range.turnedOn
.0
to 11
for hours and from 0
to 59
for minutes.import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> readBinaryWatch(int turnedOn) {
List<String> result = new ArrayList<>();
for (int h = 0; h < 12; h++) {
for (int m = 0; m < 60; m++) {
// Count the number of 1s in the binary representation of h and m
if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn) {
result.add(String.format("%d:%02d", h, m));
}
}
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
List<String> times = solution.readBinaryWatch(1);
for (String time : times) {
System.out.println(time);
}
}
}
0
to 11
(12 iterations).0
to 59
(60 iterations).Thus, the overall time complexity is O(12 * 60), which simplifies to O(720). Since 720 operations are quite manageable, the solution is efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?