AlgoPlus//structures / bit-manipulation
Read the theory

Bit Manipulation · Count Set Bits

n & (n−1) clears the lowest set bit — count in as many steps as there are 1s.

n
156
Set bits
0
Legend
Set bit (1)
Just cleared
AI Tutor Workspace
In a nutshell
Numbers are stored as binary — a row of 0s and 1s. Counting how many 1s a number has uses a neat trick: n & (n−1) erases the lowest 1 and leaves every other bit alone. Each time you apply it you've removed exactly one 1, so repeating until the number hits zero counts the 1s in as many steps as there are 1s, rather than scanning all the bits.
Ready
Press play to begin the cinematic walkthrough.
n & (n−1) clears the lowest set bit. Repeating it counts the 1-bits in as many steps as there are bits set — not the full width.
Key terms
Go deeper in the lesson
Read the full theory, intuition & complexity for Bit Manipulation · Count Set Bits.