方法一:
#include<stdio.h>
int bit_count(unsigned int n)
{
int count;
for (count = 0; n; n &= n - 1)
{
count++;
}
return count;
}
int main()
{
int y;
int c;
printf("请输入一个数:");
scanf("%d", &c);
y = bit_count(c);
printf("%d\n", y);
system("pause");
return 0;
}
方法二:
#include<stdio.h>
int bit_count(unsigned int n)
{
int count=0;
int i = 32;
while (i)
{
if (n & 1 == 1)
{
count++;
n >>= 1;
}
i--;
}
return count;
}
int main()
{
int y;
int c;
printf("请输入一个数:");
scanf("%d", &c);
y = bit_count(c);
printf("%d\n", y);
system("pause");
return 0;
}
转载于:https://blog.51cto.com/10725723/1707219