- 该题让求二进制表示数中1的个数,由于负数在右移之后计算机会在开头一位自动补上1,所以
负数右移将无法终止循环
,需要将负数转成无符号整数
class Solution {
public:
int NumberOf1(int _n) {
int res=0;
unsigned int n=_n; //负数右移后会在最高位补上1,无法结束循环
while(n){
if(n&1)res++;
n=n>>1;
}
return res;
}
};