Count the ones in a number's binary form. n & (n - 1) clears the lowest one bit, so count how many times you can do it before reaching zero.
▼The problem
LeetCode 191 (Easy). Given a positive integer n, return the number of 1 bits in its binary form (its Hamming weight).
Example: n = 11 (1011) → 3.
def hammingWeight(n):
count = 0
while n: # pins left
n &= n - 1 # knock out the lowest pin
count += 1 # one roll
return countTRY IT ON LEETCODE ▶The solution
def hammingWeight(n):
count = 0
while n: # pins left
n &= n - 1 # knock out the lowest pin
count += 1 # one roll
return countTranscript
Number of One Bits. You're given a positive integer. Count how many ones appear when it's written in binary. That count has a name: the Hamming weight.
Take eleven. In binary, that's one, zero, one, one. Picture a bowling lane with a spot for every bit, and stand a pin on each one. Three pins stand, so the answer is three.
The simple way checks one spot at a time. Read the last bit with n AND one, add it to the count, then shift n right so the next bit slides into place. Eleven takes four shifts. But this walks every spot up to the highest pin. A thirty-two bit number with one pin at the top takes thirty-two steps to count a single pin.
Brian Kernighan's trick skips the empty spots. Look at what subtracting one does. The lowest one bit flips to zero, and every zero below it flips to one. Nothing above it changes. Take twelve: one, one, zero, zero. Minus one gives one, zero, one, one. Now AND the two together. Only the bits that are one in both survive. The lowest pin is gone, and everything above it stays.
So the code is one short loop. Start the count at zero. While n is not zero, set n to n AND n minus one, and add one to the count. Every roll knocks out exactly one pin, the lowest one standing.
Back to eleven. Roll one: one, zero, one, one becomes one, zero, one, zero. Roll two: one, zero, zero, zero. Roll three: zero. The lane is clear after three rolls, so the answer is three. Now try one hundred twenty-eight: a single pin, far down the lane. Kernighan needs one roll. Bit by bit needs eight shifts.
The loop runs once per one bit, so the time grows with the number of set bits, at most thirty-two. For a fixed-size integer, that's constant. The space is constant too: just one counter.
Subtract one, AND, count the roll. That's Number of One Bits.