SDE & MLE Prep

191. Number of 1 Bits

Problem

Return the number of 1 bits in the binary form of the positive integer n (its Hamming weight).

Example: 11 (1011) → 3; 2147483645 → 30

Constraints: follow-up: the function is called many times.

Repeatedly clear the lowest set bit with n &= n − 1; count iterations.

Complexity: O(number of set bits).

class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        while n:
            n &= n - 1
            count += 1
        return count