class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n < 0:
return 0
return bin(n).count('1')
# leetcode 最优解
class Solution2(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while(n != 0):
n = n & (n - 1)
count = count + 1
return count
网友评论