# -*- 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"的個數。