Binary Watch

A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

For example, the below binary watch reads "4:51".

Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order.

The hour must not contain a leading zero.

For example, "01:00" is not valid. It should be "1:00".
The minute must be consist of two digits and may contain a leading zero.

For example, "10:2" is not valid. It should be "10:02".
Example 1:

Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
Example 2:

Input: turnedOn = 9
Output: []
Constraints:

0 <= turnedOn <= 10

思路一:左右两边,左边 [0-11],右边 [0-59],分别统计两边的 bit 位数。 turnedOn = left + right,嵌套遍历即可

private static final Map<Integer, List<Integer>> leftMap = countMap(12);
private static final Map<Integer, List<Integer>> rightMap = countMap(60);
public List<String> readBinaryWatch(int turnedOn) {
    List<String> list = new ArrayList<>();

    for (int i = 0; i <= turnedOn; i++) {
        if (leftMap.containsKey(i) && rightMap.containsKey(turnedOn - i)) {
            for (Integer x : leftMap.get(i)) {
                for (Integer y : rightMap.get(turnedOn - i)) {
                    list.add(x + ":" + ((y < 10) ? "0" : "") + y);
                }
            }
        }
    }

    return list;
}

private static Map<Integer, List<Integer>> countMap(int limit) {
    Map<Integer, List<Integer>> map = new HashMap<>();

    for (int i = 0; i < limit; i++) {
        int finalI = i;
        map.compute(Integer.bitCount(i), (k, v) -> {
            if (v == null) {
                v = new ArrayList<>();
                v.add(finalI);
            } else {
                v.add(finalI);
            }
            return v;
        });
    }

    return map;
}

思路二:看了一下题解,有更好的解法,由于总共就 10 个 bit 位,所以攻击 2**20=1024 种情况,判断每种情况是否合法,即可求解

原文地址:http://www.cnblogs.com/iyiluo/p/16855469.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性