Skip to content
StackDecode
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

  1. Binary numbers are strings of 0s and 1s; the number of 1s is called the population count or Hamming weight.
  2. Loop: clear the lowest set bit with n & (n − 1) and add one to a counter.
  3. Stop when n is 0. The counter is the answer, after one iteration per set bit.

Watch it run

Loading animation…