Counting bits
The number of 1 bits in a number is its popcount. Clearing the lowest set bit with n & (n - 1) until n is 0 counts them in as many steps as there are ones. To count over a whole range of numbers, look at each bit position separately: it repeats in blocks of 0s and 1s.
How to recognise it
- The answer depends on how many bits are set, or how many bits differ between two numbers.
- Values must be ordered or grouped by their number of set bits.
- The question sums set bits over 1..n, too many numbers to count one by one.
The idea in one picture
To count the lights that are on in a row, you could look at every switch, or you could repeatedly turn off the lowest lit one and count how many times you did it. The second way never looks at a switch that is off.
Tools
| Question | Tool |
|---|---|
| set bits in one number | loop n &= n - 1, or the built-in popcount |
bits that differ between a and b | popcount of a ^ b |
| order values by set bits | buckets by count (stable) |
total set bits in 1..n | per bit: full blocks of 2^(b+1) give 2^b each, plus the partial block |
Counting over a range
For bit b, the numbers 0..n form (n + 1) / 2^(b+1) full blocks, each with 2^b ones, plus a partial block of
(n + 1) mod 2^(b+1) numbers, which adds max(0, partial - 2^b) ones. Summing over the bits takes O(log n).
Common mistakes
- Looping
while (n > 0)on a negative number in Java or C++, which never starts; usen != 0(with unsigned in C++). - Using a comparison sort with a comparator that is not stable when equal counts must keep their order.
- Counting
1..nnumber by number whennis large.
Problems
- Minimum Bit Flips to Convert Numbereasyguide ready
- Number of 1 Bitseasyguide ready
- Sort array according to count of set bitsmediumguide ready
- Count total set bits in all numbers from 1 to nmediumguide ready