输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
//思想:用1(1自身左移运算,其实后来就不是1了)和n的每位进行位与,来判断1的个数
class Solution {
public:int NumberOf1(int n) {
int count=0;
int flag=1;
while(flag!=0)
{
if((n&flag)!=0){
count++;
}
flag=flag<<1;
}
return count;
}
};
方法2:(n - 1) & n把最右边的1变为0
class Solution {
public:
int NumberOf1(int n) {
int count = 0;
while (n != 0) {
++count;
n = (n - 1) & n;
}
return count;
}
};