LeetCode 191 Number of 1 Bits - Solution

The core idea

Two approaches:

1.1. Check each bit: AND with 1, count if set, shift right. Repeat 32 times.

2.2. Brian Kernighan's trick: n & (n - 1) clears the rightmost set bit. Count how many times you can do this before n becomes 0.

The second approach runs in O(k)O(k) where kk is the number of set bits, often faster than checking all 32 bits.