基本思路:
- 正整数转换成二进制,忘了怎么来的,搜一下,就有一个不断除二取余的方法,然后倒着数就换算过来了,但是本题只要求一的个数就行了,那就更简单了,直接上代码
代码可以优化一下的
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int main()
{
int n;
cin >> n;
vector<int> b;
for (int i = 0; i < n; i ++ ) cin >> a[i];
for (int i = 0; i < n; i ++ ) {
int cnt = 0;
while (a[i]) {
if(a[i] % 2 == 1) {
cnt ++;
}
a[i] /= 2;
}
b.push_back(cnt);
}
for(int i = 0; i < b.size(); i ++) cout << b[i] << " ";
return 0;
}