LeetCode 401. Binary Watch
考点 | 难度 |
---|---|
Backtracking | Easy |
题目
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 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.
思路
把每一分钟都检查一遍,如果符合就保存为"%d:%02d"格式。
答案
public List<String> readBinaryWatch(int num) {
List<String> times = new ArrayList<>();
for (int h=0; h<12; h++)
for (int m=0; m<60; m++)
if(Integer.bitCount(h)+Integer.bitCount(m) == num)
times.add(String.format("%d:%02d", h, m));
return times;
}