二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。
例如,上面的二进制手表读取 “3:25”。
给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。
案例:
输入: n = 1 返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
注意事项:
- 输出的顺序没有要求。
- 小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
- 分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。
https://leetcode-cn.com/problems/binary-watch/description/
一开始提交的这个,太慢了:
class Solution {
//hour0~3 代表1个数0~3的时候的时针点数
public List<String> hour0 = new ArrayList<String>(1) {
{
add("0");
}
};
public List<String> hour1 = new ArrayList<>();
public List<String> hour2 = new ArrayList<>();
public List<String> hour3 = new ArrayList<>();
//min0~5 代表1个数0~5的时候的分针点数
public List<String> min0 = new ArrayList<String>(1) {
{
add("00");
}
};
public List<String> min1 = new ArrayList<>();
public List<String> min2 = new ArrayList<>();
public List<String> min3 = new ArrayList<>();
public List<String> min4 = new ArrayList<>();
public List<String> min5 = new ArrayList<>();
/** 选择器 */
public List<String> getHourList(int type) {
switch (type) {
case 1:
return hour1;
case 2:
return hour2;
case 3:
return hour3;
default:
return hour0;
}
}
/** 选择器 */
public List<String> getMinList(int type) {
switch (type) {
case 1:
return min1;
case 2:
return min2;
case 3:
return min3;
case 4:
return min4;
case 5:
return min5;
default:
return min0;
}
}
public List<String> readBinaryWatch(int num) {
List<String> result = new ArrayList<>();
//将num拆分成不同组合
for (int i = 0; i < 4 && i <= num; i++) {
if (num - i <= 5){
//获取该组合下的时针list
List<String> hour = getHourList(i);
//获取该组合下的分针list
List<String> minute = getMinList(num - i);
//组合并添加进result
dealResult(result, hour, minute);
}
}
return result;
}
/** 初始化list */
public Solution() {
for (int i = 1; i < 60; i++) {
int temp = Integer.bitCount(i);
//int temp = countOne(i);
if (i < 12) {
getHourList(temp).add(i + "");
}
//格式化分针显示
getMinList(temp).add(String.format("%02d", i));
}
}
/** 获取1的数量 */
public int countOne(int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n - 1);
}
return count;
}
/** 组合时、分进result */
public void dealResult(List<String> result, List<String> hours, List<String> minutes) {
for (String hour : hours) {
for (String min : minutes) {
result.add(hour + ":" + min);
}
}
}
}
后来参照别人提交的作修改:
class Solution {
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 << 6) + m) == num) {
if (m < 10) {
times.add(h + ":0" + m);
} else {
times.add(h + ":" + m);
}
}
}
}
return times;
}
//或者这样
// public List<String> readBinaryWatch(int num) {
// List<String> times = new ArrayList<>();
// for (int t = 0; t < 720; t++) {
// int h = t / 60;
// int m = t % 60;
// if (Integer.bitCount((h << 6) + m) == num) {
// if (m < 10) {
// times.add(h + ":0" + m);
// } else {
// times.add(h + ":" + m);
// }
// }
// }
// return times;
// }
}