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

题目 题解|轻松解决!!!二进制中1的个数
文章图片

代码实现
#includeint 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
【题解|轻松解决!!!二进制中1的个数】然后再循环即可,x -= lastone 保险使用 x ^= lastone

    推荐阅读