191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note: x & (x-1) clears the least significant 1.
def hammingWeight(n: int) -> int:
count = 0
while n > 0:
n = n & (n-1)
count += 1
return count
Comments
Post a Comment