就是分钟保留两位小数,计算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
网友评论