401. Binary Watch

就是分钟保留两位小数,计算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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容