8 bits representing the number 7 look like this:
00000111
Three bits are set.
What are algorithms to determine the number of set bits in a 32-bit integer?
8 bits representing the number 7 look like this:
00000111
Three bits are set.
What are algorithms to determine the number of set bits in a 32-bit integer?
This can be done in
O(k)
, wherek
is the number of bits set.I think the Brian Kernighan's method will be useful too... It goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.
Java JDK1.5
Integer.bitCount(n);
where n is the number whose 1's are to be counted.
check also,
Why not iteratively divide by 2?
I agree that this isn't the fastest, but "best" is somewhat ambiguous. I'd argue though that "best" should have an element of clarity
Fast C# solution using pre-calculated table of Byte bit counts with branching on input size.