Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of 1's in binary representation

Efficient way to count number of 1s in the binary representation of a number in O(1) if you have enough memory to play with. This is an interview question I found on an online forum, but it had no answer. Can somebody suggest something, I cant think of a way to do it in O(1) time?

like image 301
TimeToCodeTheRoad Avatar asked Jan 15 '12 16:01

TimeToCodeTheRoad


People also ask

How do you count the number of 1 in binary representation?

The goal is to count the numbers less than or equal to N that have all 1's in their binary representation. For example 1 is 1, 3 is 11, 7 is 111, 15 is 1111... so on. If we see the numbers then all of them are 2i-1.


1 Answers

That's the Hamming weight problem, a.k.a. population count. The link mentions efficient implementations. Quoting:

With unlimited memory, we could simply create a large lookup table of the Hamming weight of every 64 bit integer

like image 141
Óscar López Avatar answered Sep 21 '22 17:09

Óscar López