LeetCode Problem 191.
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:
Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Constraints:
The direct way checks all 32 bits: look at n & 1, shift n right, repeat. A neater trick needs only as many steps as there are 1 bits.
Subtracting 1 from n turns its lowest 1 bit into a 0 and every 0 below it into a 1; the bits above it do not change:
n = 1011000
n - 1 = 1010111
n & (n-1) = 1010000 the lowest 1 bit is gone
So n & (n - 1) is n with its lowest 1 bit cleared. Repeat this until n becomes 0, counting the steps; the count is the number of 1 bits.
The loop must test n != 0, not n > 0. In Java the input 11111111111111111111111111111101 is the negative number -3, so n > 0 would stop before counting anything. The trick itself works on the raw bits, so negative values need no special handling.
Complexity: O(b) time, where b is the number of 1 bits (at most 32), and O(1) space.
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n != 0:
n &= n - 1 # clears the lowest 1 bit
count += 1
return count
No runs yet.