# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): # write code here cnt = 0 if n<0: n = n & 0xffffffff while n: cnt+=1 n = (n-1) & n return cnt
通过按位与,巧妙的计算出二进制中"1"的个数。
# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): # write code here cnt = 0 if n<0: n = n & 0xffffffff while n: cnt+=1 n = (n-1) & n return cnt
通过按位与,巧妙的计算出二进制中"1"的个数。