Count set bits

What does the expression n & (n - 1) compute, and how does repeatedly applying it help count set bits?

Show hints (2)+
  1. Try it on n = 12 (binary 1100).
  2. Each iteration removes exactly one 1-bit.

Answer

Reveal answer →

Clears the lowest set bit; loop counts 1-bits

Create a free account to see the full worked solution and track your progress.

Interview format: Market Maker, Prop Trading

Related questions