1)调库count
class Solution: def hammingWeight(self, n: int) -> int: return bin(n).count('1')
2)按位与,n&n-1等于去掉倒数的第一个1
class Solution: def hammingWeight(self, n: int) -> int: result = 0 while n: result += 1 n = n & n-1 return result