easyMathArrays & Hashing

Number of 1 Bits

easyTime: O(1)Space: O(1)

Recognize the pattern

count number of 1-bits in binary representationHamming weightbit clearing trick

Brute force idea

The naive version of Number of 1 Bits sounds like this: Check each of 32 bits with a mask. Not truly brute force since it's already constant time, but it checks every bit regardless. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The real unlock in Number of 1 Bits comes when you notice this: Repeatedly clear the lowest set bit with n & (n-1) — loops only as many times as there are 1-bits. For sparse numbers (few set bits), this is much faster. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

At the center of Number of 1 Bits is one steady idea: n & (n-1) always removes exactly the rightmost 1-bit. When n becomes 0, all bits have been counted. The count equals the number of iterations. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Number of 1 Bits is this: Using right-shift and checking the last bit works but doesn't stop early. The n & (n-1) trick terminates faster for numbers with few set bits. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern