方法1:
int count_bit_one(unsigned int a)
{
int count=0;
while(a)
{
if(a%2==1)
{
count++;
}
a=a/2;
}
return count;
}
int main()
{
int a=0;
int b=0;
scanf("%d",&a);
b=count_bit_one(a);
printf("count=%d\n",b);
return 0;
}
方法2:
int count_bit_one(unsigned int a)
{
int count=0;
while(a)
{
a=a&(a-1);
count++;
}
return count;
}
int main()
{
int a=0;
int b=0;
scanf("%d",&a);
b=count_bit_one(a);
printf("count=%d\n",b);
return 0;
}
方法3:
int count_bit_one(int a)
{
int count=0;
int i=0;
for(i=0;i<32;i++)
{
if(((a>>i)&1)==1)
{
count ++;
}
}
return count;
}
int main()
{
int a=0;
int b=0;
scanf("%d",&a);
b=count_bit_one(a);
printf("count=%d\n",b);
return 0;
}
标签:count,return,函数,二进制,补码,++,int,printf,bit
From: https://blog.51cto.com/u_16190077/7114870