题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
分析:
采用n = (n-1) & n相当于将补码的最后一个1变成0
对于32位整数时间O(1),空间O(1)
#c++
int NumberOf1(int n) {
int cnt = 0;
while(n){
cnt++;
n = (n-1) & n;
}
return cnt;
}
要注意一点:python的负数相当于前面有无限个1,所以必须要做负数操作。c++ int 则为有限位(32位),因此对于负数要将其位数限制在32为有了a = a & 0xffffffff操作
#python
def NumberOf1( self,a):
# write code here
#
if a < 0:
a = a & 0xffffffff
cnt = 0
while(a):
a = (a - 1) & a
cnt += 1
# print(cnt)
return cnt
补充java
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while(n != 0){
res++;
n = (n-1) & n;
}
return res;
}
}