LeetCode java-401. 二进制手表
(题目来自力扣网)
思路
暴力递归
遍历从00:00到11:59之间1 的个数
count(int n) 函数是为了遍历一个数有几个1
代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ReadBinaryWatch {
public List<String> readBinaryWatch(int num) {//num指的是亮灯的数量。亮了基站等,就有几个1
//暴力遍历 O(720),即时间复杂度为O(1)
List<String> res = new LinkedList<>();
for (int i = 0; i < 12; i++) {//遍历从00:00到11:59之间1 的个数
for (int j = 0; j < 60; j++) {
if (count(i) + count(j) == num) {
res.add(i + ":" + (j < 10 ? "0" + j : j));
}
}
}
return res;
}
public int count(int n) {//遍历一个数有几个1
int cnt = 0;
while (n != 0) {
n = n & (n - 1);
cnt++;
}
return cnt;
}
public static void main(String[] args) {
int num = 1;
System.out.println(new ReadBinaryWatch().readBinaryWatch(num));
}
}