Number of 1 Bits
Count the set bits in an unsigned integer using n & (n-1) to strip the lowest one each round.
Open on LeetCode ↗Intuition
It is tempting to loop all 32 bit positions and test each one with a shift and mask. That works, but it always costs 32 iterations no matter how sparse the number is. Notice instead what n & (n-1) does: it clears the lowest set bit and leaves everything else untouched, because subtracting 1 flips every trailing zero to one and the lowest one to zero, and ANDing with the original wipes exactly that run. So looping while n is nonzero and applying n & (n-1) each time runs once per set bit, not once per position. On a number like 128 that is one iteration instead of thirty-two. The invariant is that each round removes exactly one 1-bit, so the loop count IS the answer.
Approach
Loop while n is nonzero
Instead of iterating a fixed 32 times and checking each bit position, keep looping only as long as n still has a set bit. This ties the number of iterations directly to the number of set bits rather than to the width of the integer.
Clear the lowest set bit each round
Compute n = n & (n - 1). Subtracting 1 from n turns its lowest set bit into 0 and all bits below it into 1; ANDing with the original n then clears exactly that lowest set bit while leaving every higher bit unchanged. Increment a counter every time this happens.
Return the counter
When n reaches 0 there are no more set bits to remove, and the counter holds exactly the number of 1 bits the original number had, since each iteration removed exactly one.
Solution & live demo
Edge cases
Loop body never executes; count stays 0.
Only one set bit, so the loop runs exactly once regardless of n's magnitude.
Loop runs 32 times, once per bit, still far cheaper than testing every position when bits are sparse in general.
Use an unsigned shift or mask (e.g. n & 0xFFFFFFFF) so the sign bit does not cause infinite loops or negative comparisons.