Problem
Given an unsigned integer, count how many of its bits are set to 1 (its
Hamming weight).
Signal
"Count set bits" with no better-than-32-steps requirement is fine to brute force bit-by-bit, but the sharper tool is peeling off the lowest set bit directly — a trick worth having automatic, since it reappears any time a problem cares about "how many 1-bits" rather than "which bits."
Approach
n & (n - 1) clears exactly the lowest set bit of n (subtracting 1 flips
that bit and every trailing zero below it, and ANDing with the original wipes
just that bit). Repeat until n is 0, counting how many times you did it —
that count is the number of set bits, and you only loop once per set bit
rather than once per bit position.
Skeleton
count = 0
while n:
n &= n - 1
count += 1
return count
Solution
def hamming_weight(n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return count
Complexity
O(k) time where k is the number of set bits (at most 32) — strictly faster than checking all 32 positions when the number is sparse. O(1) space.
Pitfalls
- Shifting and checking all 32 bit positions (
for i in range(32): n >> i & 1) is also correct and a fine first answer, but it's a fixed 32 iterations regardless of how many bits are actually set — mentionn & (n-1)as the tighter version if asked to optimize. - Python's
bin(n).count('1')gets the right answer in one line and is perfectly reasonable to mention, but it's worth being able to derive the bit-trick by hand since that's usually the actual ask.