题意:
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”.
题目略长,但是很好理解,就是二进制显示时间,时间范围:【0:00 – 11:59】
好,废话不说,先上我的代码:
public class Solution {
public int int2bit(int x) {
int num = 0, temp = x;
while(temp != 0) {
if((temp & 0x01) == 0x01) {
num++;
}
temp >>= 1;
}
return num;
}
public List<String> readBinaryWatch(int num) {
if(num < 0 || num > 10) return null;
List<String> watches = new ArrayList<String>();
if(num == 0) {
watches.add("0:00");
return watches;
}
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 60; j++) {
if(int2bit(i) + int2bit(j) == num) {
if(j < 10)
watches.add(i + ":0" + j);
else
watches.add(i + ":" + j);
}
}
}
return watches;
}
}
解题思路:输入的总的LED亮灯数目是固定的,但是小时和分钟是不固定的,但是二者的LED亮灯数目之和既是固定的;而且!小时和分钟的范围是有限且固定的,因而采用最土最直接的方法,就是遍历一遍,如果二者的LED亮灯数目之和等于输入的数目,即符合要求,add进list!
但是,怎么将整型数转换成LED亮灯数呢?说白了,就是非负整型数转byte,再计算非零位总数,代码中int2bit()方法就是这个作用,运用位运算得到结果~每次右移一位与1作按位与运算,结果为1,则num+1,循环右移直至等于0,返回结果~
因篇幅问题不能全部显示,请点此查看更多更全内容