401. Binary Watch

2018-07-02  本文已影响0人  April63

就是分钟保留两位小数,计算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
上一篇下一篇

猜你喜欢

热点阅读