題目描述
輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示。
Python
class Solution:
? ? def NumberOf1(self, n):
? ? ? ? # write code here
? ? ? ? return bin(n).count('1') if n >= 0 else bin(2 **32 + n).count('1')
Python - 僅考慮正數(shù)
class Solution:
? ? ? ? cnt = 0
? ? ? ? while n > 0:
? ? ? ? ? ? if n % 2 != 0:
? ? ? ? ? ? ? ? cnt += 1
? ? ? ? ? ? n = n // 2
? ? ? ? return cnt