[AcWing 801] 二进制中1的个数

点击查看代码
#include<iostream>
using namespace std;
int lowbit(int x)
{
return x & -x;
}
int main()
{
int n;
scanf("%d", &n);
while (n --) {
int x;
scanf("%d", &x);
int res = 0;
while (x) {
x -= lowbit(x);
res ++;
}
printf("%d ", res);
}
return 0;
}
- lowbit 的作用是找到 x 的最后一位 1,返回 1 及其后面的 0,例如,x 是 10100,则 lowbit(x) 是 100;

浙公网安备 33010602011771号