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

题目

在这里插入图片描述

代码实现

#include<stdio.h>

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

猜你喜欢

转载自blog.csdn.net/Sherlook_Holmes/article/details/120622268