LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

401. 二进制手表

二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)。每个 LED 代表一个 0 或 1,最低位在右侧。

img

(图源:WikiMedia - Binary clock samui moon.jpg ,许可协议:Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)

给你一个整数 turnedOn ,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所有可能时间。你可以 按任意顺序 返回答案。

小时不会以零开头:

分钟必须由两位数组成,可能会以零开头:

示例 1:

输入:turnedOn = 1
输出:["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

示例 2:

输入:turnedOn = 9
输出:[]

解释:

位运算 简单 每日一题

枚举所有时间即可

代码

class Solution:
    def readBinaryWatch(self, turnedOn: int) -> List[str]:
        ans = list()
        for h in range(12):
            for m in range(60):
                if bin(h).count("1") + bin(m).count("1") == turnedOn:
                    ans.append(f"{h}:{m:02d}")
        return ans

我的代码循环次数比较少

        if turnedOn>8:
            return []
        mCount = {}
        for m in range(60):            
            bits = bin(m).count('1')
            s = '{:0>2d}'.format(m)
            if bits in mCount:
                mCount[bits].append(s)
            else:
                mCount[bits] = [s]
        hCount = {}
        for h in range(12):            
            bits = bin(h).count('1')
            s = '{:d}'.format(h)
            if bits in hCount:
                hCount[bits].append(s)
            else:
                hCount[bits] = [s]
        ans = []
        for i in range(turnedOn+1): # 遍历小时
            if i > 3:
                break
            if turnedOn-i>5:
                continue
            for h in hCount[i]:
                for m in mCount[turnedOn-i]:
                    ans.append(h+':'+m)
        return ans