//Optimal solution #include<stdio.h> intmain() { int n,m,s; scanf("%d",&n); while(n--) { scanf("%d",&m); s=0; while(m)//When m is not 0, it will keep looping m&=m-1,s++;//equivalent to m=m&(m-1), & is the bitwise AND operator printf("%d\n",s); } return 0; }
Calculates the result of adding two numbers x, y.
Code writing x&y
First write x and y in binary bit form~~
For example, calculate 10&30
10 binary is 1010
30 is 11110
and then start from the low bit, and each bit is AND operation separately~~
The AND operation of the bit , except 1&1=1 , the rest of the combination results are 0,
so 10&30=01010, that is, 1010. . . i.e. 10
#include<stdio.h> intmain() { int n; scanf("%d", &n); while(n--) { int m,count=0; scanf("%d", &m); while(m) { if(m%2==1) count++; m/=2; } printf("%d\n", count); } return 0; }