Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count number of ones in a given integer

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.

like image 925
Neil Avatar asked Mar 21 '13 06:03

Neil


1 Answers

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()

like image 56
TerryA Avatar answered Sep 23 '22 02:09

TerryA