Bit manipulationAnimated
Count Set Bits
Count the 1s in the binary form of a number.
Time
O(log n)
Extra space
O(1)
Use it for
Hamming weight, parity.
How it works
- Binary numbers are strings of 0s and 1s; the number of 1s is called the population count or Hamming weight.
- Loop: clear the lowest set bit with n & (n − 1) and add one to a counter.
- Stop when n is 0. The counter is the answer, after one iteration per set bit.
Watch it run
Loading animation…