← Problem setPython
#191EasyBit manipulation & math
Number of 1 Bits
The tell: Count set bits, ideally in time proportional to the number of ones.
How you get there
- 1n & (n - 1) clears the lowest set bit.
- 2Repeat until zero and count the iterations.
- 3That runs once per set bit rather than once per bit position.
Solution
def hamming_weight(n: int) -> int:
count = 0
while n:
n &= n - 1 # clears the lowest set bit
count += 1
return count- Time
- O(number of set bits)
- Space
- O(1)
What goes wrong
Shifting through all 32 positions works but is slower on sparse inputs.