输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
a&b表示 二进制码按位取与
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
#include<stack>
using namespace std;
class Solution {
public:
int NumberOf1(int n) {
int count=0,flag=1;
while(flag){
if(n&flag){//二进制码按位取与为真
count++;
}
flag = flag << 1;//左移
}
return count;
}
};
int main()
{
Solution a;
//vector<int> in = { 4, 7, 2, 1, 5, 3, 8, 6 },b;
cout << a.NumberOf1(-20);
}