Practice Discrete Math

Algorithms / Bit Count Power

Least You Need to Know: Set Bits, Powers of Two, and Lowest-Bit Tricks

Many classic bit problems rely on what happens to the **lowest set bit**. That viewpoint explains power-of-two checks, efficient bit counting, and several constant-time transformations that show up repeatedly in interviews.

The least you need to know

Key notation

popcount(x) number of 1-bits in x
x & (x - 1) clear the lowest set bit
x & -x isolate the lowest set bit

Tiny worked example

  • For `x = 12` (`1100` in binary), `x - 1 = 1011`.
  • ANDing them gives `1000`, which cleared the lowest set bit.
  • Repeating that step once per remaining 1-bit gives a fast popcount method.
  • A positive number is a power of two exactly when that clearing step leaves zero.

Common mistakes

How to recognize this kind of problem

Start practice