问题:写一个函数返回参数二进制中 1 的个数
比如: 15 0000 1111 4 个 1
程序原型:
int count_one_bits(unsigned int value)
{
// 返回 1的位数
}
以下代码都是用函数实现的,共总结了三种方法:
方法一、通过将数字整除二转化为二进制数,
需要注意的是,计算机在存储有符号的整数时,都是用该数的补码进行存储的
#include<stdio.h>
#include<windows.h>
int Count_One_Bits1(unsigned int value)
{
// 返回 1的位数
int count = 0;//记录1的个数
while (value != 0){
if (value % 2 == 1){
count++;
}
value /= 2;
}
return count;
}
int main()
{
int res=Count_One_Bits1(15);
printf("%d\n",res);
system("pause");
return 0;
}
方法二、通过移位操作符,之后按位与1可以得到1的个数,具体内容可以参考我上次总结的操作符总结
httphttps://blog.csdn.net/NEFELIBATA_Reset/article/details/90475310
#include<stdio.h>
#include<windows.h>
int Count_One_Bits2(unsigned int value)
{
int count = 0;
while(value & 1==1){
count++;
value >>= 1;
}
return count;
}
int main()
{
int res=Count_One_Bits2(15);
printf("%d\n",res);
system("pause");
return 0;
}
方法三、主要通过按位与其之前的一位数,与的次数就是1的个数
#include<stdio.h>
#include<windows.h>
int Count_One_Bits3(unsigned int value)
{
int count = 0;
while (value != 0)
{
value = value&(value - 1);
count++;
}
return count;
}
int main()
{
int res=Count_One_Bits3(15);
printf("%d\n",res);
system("pause");
return 0;
}