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.
For example, the above binary watch reads "3:25".
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".
解法如下:
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 * 64 + m) == num)
times.add(String.format("%d:%02d", h, m));
return times;
}
关于 Integer.bitCount的方法,java源码是这样的:
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
这几个位运算让我看了好一会儿才看明白。要不要解释呢?一下子我也讲不明白呢。
(i >>> 1) & 0x55555555 是 i 右移一位,然后和0101010101010101...做&与运算。。。算了,不讲了。
leetcode第191题就是关于计算一个整数的二进制有几个1,可以使用以下解法:
public int hammingWeight(int n) {
int count = 0;
while (n!=0)
{
n= n&(n-1);//此操作可以把n的最后一个1去掉
count ++;
}
return count;
}
参考 https://discuss.leetcode.com/topic/59374/simple-python-java