A binary watch has 4 LEDs onthe top which represent the hours (0-11), and the 6 LEDs on the bottomrepresent the minutes (0-59).
Each LED represents a zero orone, with the least significant bit on the right.
For example, the above binary watchreads "3:25".
Given a non-negative integer nwhich represents the number of LEDs that are currently on, return all possibletimes the watch could represent.
Example:
Input: n = 1
Return: ["1:00","2:00", "4:00", "8:00", "0:01","0:02", "0:04", "0:08", "0:16","0:32"]
Note:
The order of output does notmatter.
The hour must not contain aleading zero, for example "01:00" is not valid, it should be"1:00".
The minute must be consist oftwo digits and may contain a leading zero, for example "10:2" is notvalid, it should be "10:02".
翻译:二进制表在顶部有4个LED,表示小时(0-11),底部的6个LED表示分钟(0-59)。每个LED表示零或一,右边的最低有效位。
例如,上面的二进制表读数“3:25”。给定一个非负整数n代表当前打开的LED的数量,返回手表可能表示的所有可能的时间。
例:输入:n = 1
返 回:[“1:00”,“2:00”,“4:00”,“8:00”,“0:01”,“0:02”,“0:04”,“,“0:16”,“0:32”]
注意:
输出的顺序无关紧要。
小时不能包含前导零,例如“01:00”无效,应为“1:00”。
分钟必须由两位数字组成,并且可能包含前导零,例如“10:2”无效,应“10:02”。
题目有两个注意点,一个是二进制表,这个可以利用计算二进制的方法来思考。第二就是需要注意格式的变换。这题完全不会,参考的别人的,写的真的太好了,利用二进制的表示方法来计算时间。具体代码如下:
public class Solution {
public List<String>readBinaryWatch(int num) {
List<String> times = newArrayList<>();
for (int h=0;h<12; h++)
for (int m=0;m<60; m++)
if(Integer.bitCount(h * 64 + m) == num)
times.add(String.format("%d:%02d", h, m));
return times;
}
}