01_位1的个数
2019-11-06 本文已影响0人
butters001
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