美文网首页
401. Binary Watch

401. Binary Watch

作者: April63 | 来源:发表于2018-07-02 15:17 被阅读0次

    就是分钟保留两位小数,计算0-11和0-59分别把他们转成二进制以后计算其中数字1的个数之和是不是等于num,如果等于留下来

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

    另一种做法:
    关键是怎么计算含有1的个数
    num & num - 1

    class Solution(object):
        def readBinaryWatch(self, num):
            """
            :type num: int
            :rtype: List[str]
            """
            hour = {i:self.count1(i) for i in range(12)}
            minite = {i:self.count1(i) for i in range(60)}
            res = ["%d:%02d"%(h,m) for h in hour for m in minite if hour[h] + minite[m] == num]
            return res
        def count1(self, num):
            count = 0
            while num:
                count += 1
                num &= num - 1
            return count
    

    相关文章

      网友评论

          本文标题:401. Binary Watch

          本文链接:https://www.haomeiwen.com/subject/xahluftx.html