801. 二进制中1的个数
作者:互联网
一、利用\(x\&-x\)
#include <bits/stdc++.h>
using namespace std;
// x & -x 可以返回 x的最后一位1
//功能:返回 x的最后一位1
//用途:比如求x的二进制表示中1的个数
int lowbit(int x) {
return x & -x;
}
int main() {
int n;
cin >> n;
while (n--) {
int cnt = 0;
int x;
cin >> x;
while (x) x -= lowbit(x), cnt++;
cout << cnt << " ";
}
return 0;
}
二、遍历每一个二进制位
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
int cnt = 0;
int x;
cin >> x;
for (int i = 0; i < 32; i++)
if (x >> i & 1) cnt++;
cout << cnt << " ";
}
return 0;
}
标签:cnt,cout,二进制,++,个数,cin,int,while,801 来源: https://www.cnblogs.com/littlehb/p/15241558.html