401. Binary Watch

401. Binary Watch_第1张图片

感觉做起来很麻烦,参考了一下答案

Java,思路很清晰,直接读亮灯的位数

public List readBinaryWatch(int num) {
    List times = new ArrayList<>();
    for (int h=0; h<12; h++)
        for (int m=0; m<60; m++)
            if (Integer.bitCount(h * 64 + m) == num)
                times.add(String.format("%d:%02d", h, m));
    return times;        
}

Java,暴力

public class Solution {
        String[][] hour = {{"0"}, 
                                   {"1", "2", "4", "8"},
                   {"3", "5", "6", "9", "10"},
                   {"7", "11"}};
        String[][] minute = {{"00"}, //1
                         {"01", "02", "04", "08", "16", "32"}, //6
                         {"03", "05", "06", "09", "10", "12", "17", "18", "20", "24", "33", "34", "36", "40", "48"}, //15
                         {"07", "11", "13", "14", "19", "21", "22", "25", "26", "28", "35", "37", "38", "41", "42", "44", "49", "50", "52", "56"}, //20
                         {"15", "23", "27", "29", "30", "39", "43", "45", "46", "51", "53", "54", "57", "58"}, //14
                         {"31", "47", "55", "59"}}; //4
    public List readBinaryWatch(int num) {
        List ret = new ArrayList();
        for (int i = 0; i <= 3 && i <= num; i++) {
            if (num - i <= 5) {
                for (String str1 : hour[i]) {
                    for (String str2 : minute[num - i]) {
                        ret.add(str1 + ":" + str2);
                    }
                }
            }
        }
        return ret;     
    }
}

你可能感兴趣的:(401. Binary Watch)