版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012343179/article/details/89785955
标准思路:位运算,逻辑与。
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count=0
while n:
if n & 1:
count+=1
n=n >> 1
return count
python也可以用自带的函数做:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
n_str=str(bin(n))[2:]
n_list=[int(c) for c in n_str]
return sum(n_list)