← Bit Manipulation

Pattern Recognition Drill

#83 — Count set bits

Easy Bit Manipulation

The Problem

Count the number of 1-bits in an integer.

What approach would you use?

Think about it before scrolling down.

Key Signals

Bit Manipulation

n & (n-1) clears the lowest set bit. Loop and count until n = 0. O(number of set bits).

Common Trap

Shifting and checking each bit works (O(32)) but Kernighan's trick is more elegant.

← #82 #84 →