Pattern Recognition Drill
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.
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.