这道题用lowbit是最好的,不要用右移,因为对于负数,右移后头部添加的数字为1
/*
* 对于正数,只需要把x - lowbit(x),然后递增计数即可
* lowbit的实现,return x & -x;
*
*/
#include <iostream>
using namespace std;
int lowbit(int x){
return x & -x;
}
int onesCnt(long long x){
int n = 0;
while(x){
x = x - lowbit(x);
n ++;
}
return n;
}
int main(){
long long x = -100;
cout<<onesCnt(x)<<endl;
cout<<__builtin_popcount(x)<<endl;
return 0;
}