Skip to content
StackDecode
Bit manipulationAnimated

Brian Kernighan's Algorithm

n & (n−1) clears the lowest set bit; count how many times you can do it.

Time

O(set bits)

Extra space

O(1)

Use it for

Counting set bits quickly.

How it works

  1. Subtracting 1 from n flips the lowest set bit to 0 and every bit below it to 1.
  2. So n & (n − 1) clears exactly the lowest set bit.
  3. Repeat until n becomes 0, counting how many times you did it.
  4. The loop runs once per set bit, not once per bit position.

Watch it run

Loading animation…