题目描述:
给定一个长度为n的数列,请你求出数列中每个数的二进制表示中1的个数。
输入格式
第一行包含整数n。
第二行包含n个整数,表示整个数列。
输出格式
共一行,包含n个整数,其中的第 i 个数表示数列中的第 i 个数的二进制表示中1的个数。
数据范围
1≤n≤100000
0≤数列中元素的值≤109
输入样例:
5
1 2 3 4 5
输出样例:
1 1 2 1 2
此题也可用STL库中bitset解决,自行百度
解题思路:lowbit算法每次可以获得一个数二进制形势下最后一个1,即x&-x,每次减掉最后一个1,直到为0。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
namespace IO{
inline LL read(){
LL o=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9'){o=o*10+c-'0';c=getchar();}
return o*f;
}
}using namespace IO;
const int N=1e5+7,base=1e9;
int a[N],b[N];
int lowbit(int x){//获得最后一个1
return x&-x;
}
int main(){
int res,n,x;
n=read();
while(n--){
x=read();
res=0;
while(x){
x-=lowbit(x);//每次减掉最后一个1
res++;
}
printf("%d ",res);
}
return 0;
}