An interesting problem I came across today: what is the fastest way to count the number 1 in an n-bit integer? Is it possible to beat O (n)?
For instance:
42 = 0b101010 => 3 ones 512 = 0b1000000000 => 1 one
Clearly, the naive algorithm is simply counted. But are there any tricks to speed it up?
(This is just an academic question; when implementing such a strategy, the expected performance gain is not expected.)
source share