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
- Subtracting 1 from n flips the lowest set bit to 0 and every bit below it to 1.
- So n & (n − 1) clears exactly the lowest set bit.
- Repeat until n becomes 0, counting how many times you did it.
- The loop runs once per set bit, not once per bit position.
Watch it run
Loading animation…