How can I get the number of "1"s in the binary representation of a number without actually converting and counting ?
e.g.
def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
I'm not a python programmer, but hopefully it will be enough for you to follow.
c = 0
while n:
c += 1
n &= n - 1
return c
While a little obscure, it's primary advantage is speed and simplicity. The while loop is only iterated once for every bit set to 1 in n.