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
assert Solution().hammingWeight(11) == 3
assert Solution().hammingWeight(2147483645) == 30
class Solution {
public int hammingWeight(int n) {
int count = 0;
for (; n != 0; n &= n - 1) count++; // works for negative (unsigned) inputs too
return count;
}
}
func hammingWeight(n int) int {
count := 0
for ; n != 0; n &= n - 1 { // n & (n-1) clears the lowest set bit
count++
}
return count
}