一道经典面试题
写一个函数,求一个数二进制(补码)表示中有几个1。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int count_one(int a)
{
//算法1
//此算法有问题,无法用于负数 - 可将函数形参改为unsigned int a,使之同时满足负数
/*int count = 0;
while(a)
{
if (a % 2 == 1)
{
count++;
}
a = a / 2;
}*/
//算法2
/*int count = 0;
int i = 0;
for (i = 0; i < 32; i++)
{
if ((a >> i) & 1 == 1)
{
count++;
}
}*/
//算法3(最好)
/*int count = 0;
while (a)
{
a = a & (a - 1);
count++;
}
return count;*/
}
int main()
{
int a = 0;
scanf("%d", &a);
int count = count_one(a);
printf("count = %d\n", count);
return 0;
}