二进制中1的个数

二进制中1的个数


例题:

给定一个长度为n的数列,请你求出数列中每个数的二进制表示中1的个数。

输入格式
第一行包含整数n。

第二行包含n个整数,表示整个数列。

输出格式
共一行,包含n个整数,其中的第 i 个数表示数列中的第 i 个数的二进制表示中1的个数。

数据范围
1≤n≤100000,
0≤数列中元素的值≤109
输入样例:
5
1 2 3 4 5
输出样例:
1 1 2 1 2

解题思路

#include<iostream>
using namespace std;
const int N = 1e5 + 10;
//暴力解法
/*int get(int x){
int cnt = 0;
while(x){
if(x & 1)cnt ++;
x >>= 1;
}
return cnt;
}*/
//在计算机中是以二进制补码存储的,例如:
//负数补码为取反+1
//x = 010001
//-x = 101110
// x & (-x) 得到最后一位为1的数;
//再将其去掉,不断进行,直到没有1;
//也可等于x & (x - 1);

int lowbit(int x){
int res = 0;
while(x){
x -= (x & (-x));
res ++;
}
return res;
}

int a[N];
int main(){
int n;
cin>>n;
while(n--){
int x;
cin>>x;
cout<<lowbit(x)<<' ';
}
cout<<endl;
return 0;
}
Author: cheerfulman
Link: http://cheerfulman.github.io/2019/09/19/lowbit/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶

Comment