写一个函数返回参数二进制中 1 的个数
程序员文章站
2022-07-15 09:58:06
...
题目:写一个函数返回参数二进制中 1 的个数 。比如: 15 0000 1111 4 个 1
程序原型:
int count_one_bits(unsigned int value)
{
// 返回 1的位数
}
方法一:让数字不断移位,与1相与
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int count_one_bits(unsigned int value)
{
int count = 0;
while (value != 0)
{
if ((value & 1) == 1)
{
count++;
}
value = value >> 1;//右移一位
}
return count;
}
//for循环写法
int count_one_bits(unsigned int value)
{
int count = 0;
for (; value != 0; value = value >> 1)
{
if ((value & 1) == 1)
{
count++;
}
}
return count;
}
int main()
{
int num = 0;
scanf("%d", &num);
int count = count_one_bits(num);
printf("%d", count);
system("pause");
return 0;
}
另一种方法:让1不断左移,与数字相与
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
//方二:另1左移
int CountBit(int x)
{
int i = 0;
int count = 0;
int top = sizeof(x)* 8;
for (; i < top; i++)
{
if ((x & (0x1<<i))!=0)
{
count++;
}
}
return count;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = CountBit(n);
printf("%d", ret);
system("pause");
return 0;
}