AcWing 801. 二进制中1的个数

x = x & (x - 1)去除最低位的1
x &= x - 1这个操作会精确地消除x的最低位的1
因此每次执行这个操作时,x中确实有一个1被消除了
所以可以直接count++,因为每次操作都对应一个真实的1

代码

#include <bits/stdc++.h>
using namespace std;
// const int N = 100010;
// int a[N];

int main()
{
    int n, x;
    cin >> n;
    for (int i = 0; i < n; i ++ )
    {
        cin >> x;
        int cnt = 0;
        while (x)
        {
            x = x & (x - 1);
            cnt++;
        }
        cout << cnt << " ";
    }
    
    
    return 0;
}
posted @ 2025-08-01 14:33  Roin_Long  阅读(3)  评论(0)    收藏  举报