写一个函数返回参数二进制中 1 的个数
比如: 15 0000 1111 4 个 1
- 方法一:
#include <stdio.h>
#include <stdlib.h>
int CountBit(int n)
{
int count = 0;
while (n)
{
if (n % 2 == 1) {
++count;
}
n = n >> 1;
}
return count;
}
int main()
{
int ret = CountBit(10);
printf("ret=%d", ret);
system("pause");
return 0;
}
- 不过方法1只能在并不是适用所有数变成-10就会错误。下面我就用第二种方法来实现。
方法二
#include <stdio.h>
#include <stdlib.h>
int CountBit(int n)
{
int count = 0;
for (int i = 0; i < 32; i++)
{
if (n&(1 << i))
{
++count;
}
}
return count;
}
int main()
{
int ret = CountBit(-20);
printf("ret=%d", ret);
system("pause");
return 0;
}
通过这种方法就没有问题了。