Learn / Bit manipulation

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

QuestionTool
set bits in one numberloop n &= n - 1, or the built-in popcount
bits that differ between a and bpopcount of a ^ b
order values by set bitsbuckets by count (stable)
total set bits in 1..nper 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; use n != 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..n number by number when n is large.

Problems

0 of 4 solved

Check yourself

How many times does the loop n = n & (n - 1) run for n = 22 (binary 10110)?

How many bits must be flipped to turn 10 (1010) into 7 (0111)?

Counting set bits in 0..n, how does bit 0 behave?