注意正数与负数都必须能判断
思路:把一个整数减去1,再和原整数做与运算,会把该整数最右边的一个1变成0;
#include<iostream>
#include<string>
using namespace std;
int numberof1(int n){
int count = 0;
while (n){
count++;
n = n&(n - 1);
}
return count;
}
void main(){
int n;
cin >> n;
cout << numberof1(n) << endl;
system("pause");
}