LeetCode 401 Binary Watch

题意:  一块表,上面有四个灯,分别显示8、4、2、1;下面有六个灯,分别显示32、16、8、4、2、1。

    上面的灯代表小时,下面的灯代表分钟,给你数字n,代表有n个灯亮,让你求出n个灯亮可能代表的时间是多少。

    (小时范围是0到11,分钟范围是0到59)

我的思路:  用数组记录一定数量灯亮的时候代表的是多少小时(分钟)。比如,

       upLight[2].time存储的是上面2个灯亮的时候可能的小时数为3、5、9、6、10

       downLight[2].time存储的是下面2个灯亮的时候可能的分钟数2、5、9、17、33、6、10、18、34、12、20、36、24、40、48。

    

public class Solution {
     class Light {
        List<Integer> time = new ArrayList<Integer>();
    }
    
    private Light[] upLight = new Light[12];
    private Light[] downLight = new Light[60];
    
    public List<String> readBinaryWatch(int num) {
        List<String> ans = new ArrayList<String>();
        init(11, upLight);
        init(59, downLight);
        for(int up = 0; up <= num; up++) {
            int down = num-up;
            for(int hour : upLight[up].time) {
                for(int min: downLight[down].time) {
                    if (min >= 10) ans.add("" + hour + ":" + min);
                    else ans.add("" + hour + ":0" + min);
                }
            }
        }
        return ans;
    }
    
    public void init(int k, Light[] light) {
        for(int i = 0; i <= k; i++) {
            light[i] = new Light();
        }
        
        for(int i = 0; i <= k; i++) {
            int t = i;
            int cnt = 0;
            while(t > 0) { // 利用二进制
                if(t%2==1) cnt++;
                t >>= 1;
            }
            light[cnt].time.add(i);
        }
    }
}

  

原文地址:https://www.cnblogs.com/sevenun/p/5896139.html