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

image


点击查看代码
#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;
}

  1. lowbit 的作用是找到 x 的最后一位 1,返回 1 及其后面的 0,例如,x 是 10100,则 lowbit(x) 是 100;
posted @ 2022-04-27 16:57  wKingYu  阅读(31)  评论(0)    收藏  举报