轻松解决!!!二进制中1的个数

题目

轻松解决!!!二进制中1的个数_第1张图片

代码实现

#include

int main(){
     
    int n;scanf("%d",&n);
    while(n--){
     
        int count = 0;
        int x;scanf("%d",&x);
        while(x){
     
            x ^= x & -x;//x -= x & -x;
            count ++;
        }
        printf("%d ",count);
    }
    return 0;   
}

分析

lowbit(x)是x的二进制表达式中最低位的1所对应的值。

int lastone =-x & -x 算出最后一位1

然后再循环即可,x -= lastone 保险使用 x ^= lastone

你可能感兴趣的:(题解,c语言)