问题描述:
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.
输出格式限定:
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”.
思路:
一个时间由两部分组成:时针+分针
我们如何判断一个时针,或者一个分针,需要亮几个灯?
如上图所示:为了表示分针51=32+16+2+1,需要亮四个灯;为了表示时针4,需要亮1个灯。我们可以把亮灯的数量转化为一个整数的二进制表达中1的数量。比如51的二进制表达为110011,它有4个1,所以对应亮4个灯
代码如下:
class Solution {
public List<String> readBinaryWatch(int turnedOn) {
List<String> list = new ArrayList<>();
for(int h=0; h<=11; h++){
for(int m=0; m<=59; m++){
if(countOne(h)+countOne(m)==turnedOn){
String hour= Integer.toString(h);
String min= m<10? "0"+Integer.toString(m):Integer.toString(m);
list.add(hour+":"+min);
}
}
}
return list;
}
private int countOne(int n){
//this function counts # of 1 in O(logn)
int counter=0;
while(n>0){
if((n&1)==1){
counter++;
}
n=n>>1;
}
return counter;
}
}
时间复杂度: O(720logn)=O(logn)