给定一个整数,统计其二进制表示里有多少个1。
def count1(num):
lens = 0
while num != 0:
lens += num & 1
num >>= 1
return lens
def count(self,num):
lens = 0
while num != 0:
num = num & (num - 1) # 本质含义是抹去了0不考虑
lens += 1
return lens
python 可以直接通过bin()方法获得一个树的二进制表示,返回值是一个字符串,因此
bin(x).count(‘0‘)也可以做到上述结果
原文:https://www.cnblogs.com/r1-12king/p/13042547.html