PracticeNeetCode ↗LeetCode ↗
Given a positive integer n, return the number of set bits (1s) in its binary representation — the Hamming weight.
n & (n - 1) clears exactly the lowest set bit of n — a trick worth memorizing on its own.count = 0.n is nonzero: set n = n & (n - 1), clearing its lowest 1-bit, and increment count.n reaches 0, every set bit has been cleared and counted.count.Time: O(k) where k is the number of set bits — Space: O(1)
def hammingWeight(n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return countHow the solution above works, piece by piece.
n - 1 flips the lowest set bit to 0 and every bit below it to 1.n &= n - 1 clears exactly the lowest set bit.n becomes 0: that's the number of 1 bits.Running it on n = 11 (binary 1011):