[LeetCode]401. Binary Watch

题目

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


For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:

Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

Note:

  • The order of output does not matter.
  • 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".

难度

Easy

方法

遍历所有可能的时间,如果其中1的个数等于n,则将该时间加入返回的结果列表中

python代码

class Solution(object):
    def readBinaryWatch(self, num):
        """
        :type num: int
        :rtype: List[str]
        """
        result = []
        for i in range(12):
            for j in range(60):
                if bin(i).count("1") + bin(j).count("1") == num:
                    result.append("%d:%02d" % (i, j))
        return result

assert Solution().readBinaryWatch(1) == ["0:01", "0:02", "0:04", "0:08", "0:16", "0:32", "1:00", "2:00", "4:00", "8:00"]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,410评论 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 14,593评论 5 6
  • 看了我是歌手,这期,挺好 1李健唱的挺好,真的让我想到了自己的父亲,“希望他们长大以后不要那么艰难。”心理很激动,...
    juan目的导向阅读 877评论 0 0
  • 阿难对佛祖说 :我喜欢上了一女子. 佛祖问阿难:你有多喜欢这女子? 阿难说:我愿化身石桥,受五百年风吹,五百年日晒...
    叶塞尼娅阅读 3,064评论 0 1
  • 下一次路过的时候记得告诉我 你想去往何处旧房子窗外的那树玉兰凋落了几朵 如果依然是在午夜我希望见到那家牵魂的小店影...
    2020号阅读 3,008评论 33 33