题目
Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
解题思路
每次&1判断是否最后一位为1,之后右移一位
代码
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n:
res += n & 1
n >>= 1
return res