Skip to content

Latest commit

 

History

History
64 lines (53 loc) · 1.35 KB

401.md

File metadata and controls

64 lines (53 loc) · 1.35 KB
public class Solution {

    public static void main(String[] args) {
        System.out.println(new Solution().readBinaryWatch(9));
    }

    private boolean[] time = new boolean[10];

    public List<String> readBinaryWatch(int turnedOn) {

        List<String> res = new ArrayList<>();
        dfs(res, turnedOn, 0);
        return res;
    }

    private void dfs(List<String> res, int n, int idx) {
        if (n == 0) {
            String hs = getH() + "";
            int m = getM();
            String ms = m < 10 ? "0" + m : m + "";
            res.add(hs + ":" + ms);
            return;
        }

        for (int i = idx; i < time.length; i++) {

            time[i] = true;
            if (getH() >= 12) {
                time[i] = false;
                continue;
            }
            if (getM() >= 60) {
                time[i] = false;
                continue;
            }
            dfs(res, n - 1, i + 1);
            time[i] = false;
        }
    }

    private int getH() {
        int h = 0;
        for (int i = 0; i <= 3; i++) {
            if (time[i]) {
                h += 1 << (3 - i);
            }
        }
        return h;
    }

    private int getM() {
        int m = 0;
        for (int i = 4; i <= 9; i++) {
            if (time[i]) {
                m += 1 << (9 - i);
            }
        }
        return m;
    }

}