解题思路:
(1)因为左移会改变符号,因此这里考虑右移
(2)因为二进制无论是原码还是补码,当最后一位是0时,该整数必能整除2
(3)非负数,每次右移一位,补0,不改变1的个数,只有当被移位是1时才会改变
(4)负数(补码)每次右移一位,补1,增加1的个数,可以反其道而行之,我们计算出0的个数,再使用32减去该值
class Solution {
public:
int NumberOf1(int n) {
int count = 0;
if (n>=0) {
while(n!=0) {
if (n%2!=0) count++;
n = n >> 1;
}
return count;
} else {
while(n!=-1) {
if (n%2==0) count++;
n = n >> 1;
}
return 32-count;
}
return count;
}
};