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 n which represents the number of LEDs that are currently on, return all possible times 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 not matter.
The hour must not contain a leading zero, for example “01:00” is not valid, it should be “1:00”.
The minute must be consist of two digits and may contain a leading zero, for example “10:2” is not valid, it should be “10:02”.
Subscribe to see which companies asked this question
解法一:Language-Java Time-O(1) Space-O(n) Run Time-34ms
算法思路:
h*64+m刚好拼成一个“时钟+分钟”的二进制串,其中1的个数=num的时间即为所求的时间
注意:乘法可以用位运算来解决,这样效率更高。例如本题中h*64可以写成h<<6
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> list = new ArrayList<String>();
for(int h = 0; h < 12; h ++)
{
for(int m = 0; m < 60; m ++)
{
if(Integer.bitCount(h * 64 + m) == num)//bitCount:返回二进制串中1的个数
{
list.add(String.format("%d:%02d", h, m));
}
}
}
return list;
}
}
解法二:Language-Java Time-O(1) Space-O(n) Run Time-35ms
解题思路:
遍历0-0x2FC之间的数,看哪些数的bitCount满足条件,即为所求解
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> res = new ArrayList<String>();
for(int i = 0; i < 0x2FC; i ++)
{
//分钟要小于60
if(Integer.bitCount(i) == num && (i&0x03F)<60)
{
res.add(String.format("%d:%02d", i >> 6, i & 0x03F));
}
}
return res;
}
}