法一:
def count_bit(x):
count = 0
le = len(bytes(x)[2:])
for i in range(le):
res = x % 2
# print(res)
if res == 1:
count += 1
x = x >> 1
return count
print(count_bit(7))
法二:
def count_bit2(x):
count = 0
while x > 0:
res = x & 1
if res == 1:
count += 1
x = x >> 1
return count
print("#",count_bit2(7))