401. Binary Watch

就是分鐘保留兩位小數(shù),計(jì)算0-11和0-59分別把他們轉(zhuǎn)成二進(jìn)制以后計(jì)算其中數(shù)字1的個(gè)數(shù)之和是不是等于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]

另一種做法:
關(guān)鍵是怎么計(jì)算含有1的個(gè)數(shù)
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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容