//最优解
#include<stdio.h>
int main()
{ int n,m,s;
scanf("%d",&n);
while(n--)
{
scanf("%d",&m);
s=0;
while(m)//当m不为0时便一直循环
m&=m-1,s++;//相当于m=m&(m-1),&是位与运算符
printf("%d\n",s);
}
return 0;
}
计算两个数x,y相与的结果。
代码写作x&y
先将x与y分别写成二进制bit形式~~
例如计算10&30
10二进制为1010
30为11110
然后从低位开始,每个bit分别作与运算~~
其中bit的与运算,除了1&1=1外,其余组合结果均为0
故10&30=01010,即1010。。。也就是为10
#include<stdio.h>
int main()
{
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;
}