面試15題:
題目:二進制中1的個數
題:輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼表示。
解題思路一:
最佳方法:把一個整數減去1,再和原整數做“與運算”,會把該整數最右邊的1變成0。那么一個整數的二進制中表示中有多少個1,就可以進行多少次這樣的操作。
解題代碼:
# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): # write code here count=0 if n < 0: n=n & 0xffffffff while (n): n=(n-1) & n count += 1 return count
注意:如果該整數是負數,要把它和0xffffffff相與,消除負數的影響。
解題思路二:利用Python特性
解題代碼:
# -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): # write code here return bin(n&0xffffffff).count("1")