思路
首先知道一个操作,就是求一个数的二进制中最后一位1,做法是b&(-b),c++中-b的二进制码就是~b+1,
如果b是10010 ,那么-b就是01101+1=01110,那么b&(-b)就是00010,就得到了只有b最后一位1的数,让b减去该数,在重复以上过程,知道b为0,做了几次就有几个1。
代码
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
const int N = 1e5 + 7;
int a[N], b[N];
int main() {
int n, b;
cin >> n;
for (int i = 0; i<n; i++) {
cin >> b;
int ans = 0;
while (b) {
b -= (b&(-b));
ans++;
}
cout << ans << " ";
}
return 0;
}