一个数-1后和本身异或可以消掉最右边的1
# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): # 抹掉最右边的一个1 count = 0 if n < 0: n = n & 0xFFFFFFFF while n: n = (n - 1) & n count += 1 return count