Math Fundamentals18 sections · 814 units
Open in Course

Count Bits - Brian Kernighan Trick

Flip rightmost 1

A faster approach: repeatedly flip the rightmost 1 bit to 0 until nn becomes 0. The number of flips equals the number of 1 bits.

The operation n&(n1)n \& (n - 1) flips the rightmost 1 bit to 0. Why? Subtracting 1 flips all trailing bits up to and including the rightmost 1. ANDing with nn zeros out that rightmost 1. For example, 1100&1011=10001100 \& 1011 = 1000.

Loop: while n>0n > 0, do n:=n&(n1)n := n \& (n - 1) and increment a counter. When nn reaches 0, all 1s have been flipped. This runs in O(k)O(k) where kk is the number of 1 bits, not O(32)O(32).