Description
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"
.
Examples:
Example 1:
Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
Example 2:
Input: turnedOn = 9
Output: []
Solution in Python
Thought Process:
- LED Representation:
- Use a total of 10 bits: the first 4 for hours and the last 6 for minutes.
- Count the number of set bits (1s) in these 10 bits to determine the LEDs turned on.
- Constraints:
- The hour should be in the range
0-11
(valid with 4 bits). - The minute should be in the range
0-59
(valid with 6 bits). - Ensure that the hour and minute formatting complies with the problem description (e.g., “2:07” instead of “2:7”).
- The hour should be in the range
- Generate All Possibilities:
- Loop through all possible combinations of hours and minutes.
- Count the number of set bits in each combination using Python’s
bin()
function.
- Filter Valid Results:
- Include only those combinations where the total number of set bits equals
turnedOn
.
- Include only those combinations where the total number of set bits equals
- Output:
- Format the valid times in the “hour:minute” format.
Python
class Solution:
def readBinaryWatch(self, turnedOn: int) -> List[str]:
# List to store all possible times
results = []
# Loop through all possible hours (0-11)
for hour in range(12):
# Loop through all possible minutes (0-59)
for minute in range(60):
# Count the total number of LEDs turned on
if bin(hour).count('1') + bin(minute).count('1') == turnedOn:
# Format the time as "hour:minute" with proper zero padding for minutes
results.append(f"{hour}:{minute:02d}")
# Return all valid times
return results
Explanation of the Code:
- Outer Loop:
- Iterate over possible
hour
values from0
to11
.
- Iterate over possible
- Inner Loop:
- Iterate over possible
minute
values from0
to59
.
- Iterate over possible
- Count LEDs:
- Use Python’s
bin(x).count('1')
to count the number of1
s in the binary representation ofhour
andminute
.
- Use Python’s
- Filter by
turnedOn
:- Check if the total number of set bits equals the given
turnedOn
.
- Check if the total number of set bits equals the given
- Format Time:
- Use
f"{hour}:{minute:02d}"
to format the time correctly.minute:02d
ensures that the minute always has two digits (e.g., “2:07”).
- Use
- Result:
- Append valid times to the result list.
Solution in C++
C++
class Solution {
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string> result; // Stores all valid times
// Iterate over all possible hours (0-11)
for (int hour = 0; hour < 12; ++hour) {
// Iterate over all possible minutes (0-59)
for (int minute = 0; minute < 60; ++minute) {
// Count the total number of LEDs turned on
int count = bitset<10>(hour << 6 | minute).count();
if (count == turnedOn) {
// Construct the time string in "h:mm" or "h:0m" format
result.push_back(to_string(hour) + ":" + (minute < 10 ? "0" : "") + to_string(minute));
}
}
}
return result;
}
};
Solution in Javascript
JavaScript
var readBinaryWatch = function(turnedOn) {
// Initialize an array to store all possible valid times
let result = [];
// Loop through all possible hour values (0 to 11)
for (let hour = 0; hour < 12; hour++) {
// Loop through all possible minute values (0 to 59)
for (let minute = 0; minute < 60; minute++) {
// Calculate the total number of LEDs turned on for this hour and minute
let ledCount = countBits(hour) + countBits(minute);
// If the total number of LEDs matches the input `turnedOn`, it's a valid time
if (ledCount === turnedOn) {
// Format the time as "hour:minute" (minute should be two digits)
let time = `${hour}:${minute.toString().padStart(2, '0')}`;
result.push(time);
}
}
}
// Return the array of valid times
return result;
};
function countBits(num) {
let count = 0;
while (num > 0) {
count += num & 1; // Check if the last bit is 1
num >>= 1; // Right-shift to remove the last bit
}
return count;
}
Solution in Java
Java
class Solution {
/**
* Returns all possible times a binary watch can represent with a given number of LEDs turned on.
*
* @param turnedOn The number of LEDs that are currently on.
* @return A list of possible times as strings in "H:MM" format.
*/
public List<String> readBinaryWatch(int turnedOn) {
// List to store all possible valid times.
List<String> result = new ArrayList<>();
// Iterate over all possible hour (0 to 11) and minute (0 to 59) combinations.
for (int hour = 0; hour < 12; hour++) {
for (int minute = 0; minute < 60; minute++) {
// Count the number of bits that are set to 1 in the binary representation of hour and minute.
if (Integer.bitCount(hour) + Integer.bitCount(minute) == turnedOn) {
// Format the time string as "H:MM" and add it to the result list.
result.add(String.format("%d:%02d", hour, minute));
}
}
}
return result;
}
}