方法1:
int CountNumOf1(int digital)
{
int num = 0;
while(digital)
{
if(digital % 2 == 1)
{
num ++;
}
digital /= 2;
}
return num;
}
方法2:
int CountNumOf1(int digital)
{
int num = 0;
while(digital)
{
num += (digital % 2) ? 1: 0;
digital /= 2;
}
return num;
}
方法3:
int CountNumOf1(int digital)
{
int num = 0;
while(digital)
{
num += digital & 0x01;
digital >>= 1;
}
return num;
}
方法4:
int CountNumOf1(int digital)
{
int num = 0;
while(digital)
{
digital &= (digital - 1);
num++;
}
return num;
}
int main(void)
{
int n;
scanf("%d",&n);
printf("%d ",CountNumOf1(n));
return 0;
}
本文出自 “sunnyting” 博客,转载请与作者联系!
原文地址:http://sunnyting.blog.51cto.com/8814143/1564424