Open box-lin opened 1 year ago
n & (n-1) = n with flip the least significant 1 to 0
n & (n-1)
n=1000
n-1 = 0111
n & (n-1) = 0
n=1110
n-1 = 1101
n & (n-1) = 1100
class Solution: def hammingWeight(self, n: int) -> int: ans = 0 while n > 0: n &= (n-1) ans += 1 return ans
n & (n-1)
= n with flip the least significant 1 to 0n=1000
thenn-1 = 0111
,n & (n-1) = 0
n=1110
thenn-1 = 1101
,n & (n-1) = 1100
191. Number of 1 Bits