Math Fundamentals18 sections · 814 units
Open in Course

Count Bits - Brian Kernighan's Algorithm

Clever bit trick

Here's a faster way: repeatedly clear the rightmost set bit until nn becomes 0. Count how many times you clear a bit.

The trick is n&(n1)n \& (n - 1). This expression clears the rightmost 1 bit in nn. Why? When you subtract 1 from nn, the rightmost 1 becomes 0 and all bits to its right become 1. ANDing with the original nn cancels them out.

Example: n=12=1100n = 12 = 1100. Compute n1=11=1011n - 1 = 11 = 1011. Then n&(n1)=1100&1011=1000=8n \& (n-1) = 1100 \& 1011 = 1000 = 8. The rightmost 1 is gone. This algorithm runs in O(k)O(k) time where kk is the number of set bits, not O(32)O(32).