class Solution:
def hammingWeight(self, n: int) -> int:
#将整数转化为二进制
res = 0
while n>0:
res+=(n%2)
n = n//2
return res
#n&n-1会把最后一个1变为0
ret = 0
while n:
n &= n - 1
ret += 1
return ret
return bin(n).count('1')
- The method of converting integers to binary, counting the number of ones
- Use n&n-1 to change the last digit to 1 to count the number of 1s
- Use the bin(n) API to directly convert integers to binary strings and count the number of 1