https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
// 使用与(&)运算,即两位同时为1时结果才为1
return n == 0 ? 0 : 1 + hammingWeight(n & (n - 1));
}
}
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
# bin() 函数返回一个 int 或者长整型 long int 的二进制表示
for i in str(bin(n)):
if i == '1': count += 1
return count