位运算

7.位运算


二进制中1的个数

在这里插入图片描述

输入样例:

5
1 2 3 4 5

输出样例:

1 1 2 1 2

模板:

// lowbit操作 : 返回 x 的最后一位 1
//二进制中 1 的个数 
#include<iostream>
#include<cstdio>
using namespace std;
int lowbie(int x){   //lowbit x 可以返回 x 的最后一位 1  
	return x & -x;   // & 与运算符  -x = ~x+1(取反 x +1) 
}

int main(){
	int n;
	cin>>n;
	while(n--){
		int x;
		cin>>x;
		
		int res=0;
		while(x) x-=lowbie(x) res++;
		
		cout<<res<<endl;
	}
}

 

posted @ 2022-03-22 00:46  panse·  阅读(13)  评论(0)    收藏  举报