华为机试-二进制中1的个数(HJ62)——纯C
查找输入整数二进制中1的个数
https://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad?tpId=37&&tqId=21285&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking
纯C
核心:n &= (n-1)为真的次数,即为二进制中1的个数,详见《编程之美》
#include <stdlib.h> #include <stdio.h> int main() { int n; while(scanf("%d", &n) != EOF) { int count = 0; while(n) { n &= (n-1); count++; } printf("%d\n", count); } return 0; }