题目描述:
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
思路:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2y.
思路1:
举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从原来整数最右边一个1那一位开始所有位都会变成0。如1100&1011=1000.也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。
Python实现:
// An highlighted block
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
flag = 1
count = 0
maxBit = 32
for i in range(maxBit):
if n & flag:
count+=1
flag = flag<<1
return count
思路:flag与
实现2:
// An highlighted block
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
return sum([(n>>i & 1) for i in range(0,32)])