位运算
n &= n - 1 : 能让二进制最后一位1 变为0
n = n & ((1 << 32) - 1) : 能让整数(正负数)变成无符号整数
class Solution(object):
def NumberOf1(self,n):
"""
:type n: int
:rtype: int
"""
count = 0
n = n & ((1 << 32) - 1)
while n:
count += 1
n &= n - 1
return count
n >>= 1 : 能让正整数二进制进行无符号右移
class Solution(object):
def NumberOf1(self,n):
count = 0
n = n & ((1 << 32) - 1)
while n:
count += n & 1
n >>= 1
return count