LeetCode #191 Easy

Number of 1 Bits

Count the set bits in an unsigned integer using n & (n-1) to strip the lowest one each round.

bit-manipulation
Open on LeetCode ↗
02

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.

03

Approach

1

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.

2

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.

3

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.

04

Solution & live demo

python
1class Solution:
2 def hammingWeight(self, n: int) -> int:
3 count = 0
4 while n:
5 n &= (n - 1)
6 count += 1
7 return count
05

Edge cases

n = 0

Loop body never executes; count stays 0.

n is a power of two (e.g. 128)

Only one set bit, so the loop runs exactly once regardless of n's magnitude.

n = 0xFFFFFFFF (all bits set)

Loop runs 32 times, once per bit, still far cheaper than testing every position when bits are sparse in general.

n treated as unsigned in languages with signed ints

Use an unsigned shift or mask (e.g. n & 0xFFFFFFFF) so the sign bit does not cause infinite loops or negative comparisons.

06

Complexity

Time
O(k) where k is the number of set bits (at most 32)
Space
O(1)
undefined