The problem, in one line. Given a positive whole number, count how many of its binary digits are 1. LeetCode 191.
The tell. The question is about the binary form of a number, not its size. When the answer depends on which switches are on, reach for AND, shift and subtract-one tricks.
The wrong first idea
Look at the lowest bit, count it, slide the whole row one place right, and repeat until nothing is left.
count = 0
while n:
count += n & 1
n >>= 1
return count
It is correct. It takes one step per bit of the number, including every zero. For a number like 2,147,483,648, which is a single 1 followed by thirty-one 0s, that is 32 steps to find one switch. The loop spends most of its time stepping over zeros.
The invariant
Subtracting 1 from a number flips its lowest 1 bit to 0 and turns every 0 below it into 1. AND-ing the result with the original clears exactly that lowest 1 and touches nothing above it.
n = 1 0 1 1 0 0
n - 1 = 1 0 1 0 1 1
n & (n - 1) = 1 0 1 0 0 0 one bit gone
The sentence that stays true every step: each pass of the loop removes exactly one 1 bit, so the number of passes equals the number of 1 bits. The zeros cost nothing.
The solution
def hamming_weight(n):
count = 0
while n:
n &= n - 1 # drops the lowest 1 bit
count += 1
return count
print(hamming_weight(13))
print(hamming_weight(64))
print(hamming_weight(2**31 - 3))
3
1
30
func hammingWeight(n uint32) int {
count := 0
for n != 0 {
n &= n - 1 // drops the lowest 1 bit
count++
}
return count
}
Same three calls print 3, 1, 30.
Complexity
- Time O(k), where k is the number of 1 bits and never more than 32, so O(1) for a 32-bit input.
- Space O(1): one counter.
Traps
- Looping
while n > 0on a signed value in a language where the top bit means negative. A number with bit 31 set looks negative and the loop never runs, so take an unsigned type as the Go version does. - Writing
n & (n - 1) == 0in C or Java, where comparison binds tighter than&. It testsn - 1 == 0first, so 64 is judged wrongly. Add the brackets. - Using a loop that runs once before testing
n. Thenhamming_weight(0)returns 1 when the right answer is 0.
Next in the ladder
Counting Bits asks for this count for every number from 0 up to n, and the trick becomes reusing the answers you already have.