401. Binary Watch
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"]
还算有趣的题目,而且这手表不错,不知道哪里有。
一开始看,就感觉等同于一道题目,求一个范围内的二进制数中1的个数限定的数
这个题目的解法我一直没很好的掌握,上蠢办法,范围内全部遍历
public class Solution {
public List<String> readBinaryWatch(int num) {
List<String> answer = new ArrayList<>();
for(int i=0;i<1024;++i){
int curNum=0;
int cur=i;
while(cur!=0){
curNum+=cur&1;
cur>>=1;
}
if(curNum==num && i%64<=59 && i/64<=11){
answer.add(String.format("%d:%02d",i/64,i%64).toString());
}
}
return answer;
}
}