int main() { int n = 0; scanf("%d", &n); int count = 0; while(n) { if (n % 2 == 1) { count++; } n /= 2; } printf("%d", count); return 0; }
#include<stdio.h> int main() { int n = 2; scanf("%d", &n); int t = 1; int count = 0; while(t) { if ((n & t) != 0)//n 与 1比较看该位置上是否有两个1,若n没有则会被与成0 { count++; } t <<= 1;//让t不断后移测每一位数是有1 } printf("%d", count); return 0; }
int main() { int n = 0; scanf("%d", &n); int count = 0; while (n) { n = n & n - 1;//n-1减去一位并与n与将会得到 除去了最后面一个1的二进制 count++; } printf("%d", count); return 0; }