count number of ones in a given integer

python, python-2.7

Solution

Use the awesome `collections` module.

>>> from collections import Counter
>>> binary = bin(20)[2:]
>>> Counter(binary)
Counter({'0': 3, '1': 2})

Or you can use the built-in function `count()`:

>>> binary = bin(20)[2:]
>>> binary.count('1')
2

Or even:

>>> sum(1 for i in bin(20)[2:] if i == '1')
2

But that last solution is slower than using `count()`

Problem

How do you count the number of ones in a given integer's binary representation. Say you are given a number `20`, which is `10100` in binary, so number of ones is 2.

Original source