How to count the total bits of a number that equal to one (1) in Python

1 Answer

0 votes
def count_bits(n): 
    count = 0
    while (n): 
        count += n & 1
        n >>= 1
    return count 
  
  
n = 1358

print(bin(n))

print(count_bits(n))


'''
run:

0b10101001110
6

'''

 



answered Mar 5, 2019 by avibootz
...