您的位置:首页 > 其它

写一个函数返回参数二进制中 1 的个数

2018-04-11 22:14 260 查看
思路一:一个数取模的结果就是最低比特位,如果取模是1,则计数。然后把这个数除以2(即去掉最低比特位),再判断。

但是这个程序有局限性,只能判断正数。
#include<stdio.h>
#include<windows.h>
int countBit(int i)
{ int c = 0;
while (i)
{ if (i % 2 == 1)//判断最低比特位
{
c++;
}
i/= 2;//去掉最低比特位 }
return c;
}
int main()
{
int i = 254;
int c = countBit(i);
printf("%d", c);
system("pause");
return 0;
}思路二:把这个数与1按位与(两个操作数同时为1,&结果为1),然后再右移移位,再判断其他位。但是这个方法必须循环32次。
#include<stdio.h>
#include<windows.h>
int countBit(int i)
{
int c = 0;
int n = 0;
while (n<32)
{
if (i&1)//判断最低比特位
{
c++;
}
i >>= 1;//去掉最低比特位
n++;
}
return c;
}
int main()
{
int i = 254;
int c = countBit(i);
printf("%d", c);
system("pause");
return 0;
}
三(最优方法):把这个数减一,再&1
#include<stdio.h>
#include<windows.h>
int count_one_bits(unsigned int value)
{
int count = 0;
while (value)
{
value = value&(value - 1);
count++;
}
return count;//通过return返回,只能返回一个值,并且返回执行权。
}
int main()
{
int value = 254;
int count = count_one_bits(value);
printf("二进制中1的个数:%d\n", count);
system("pause");
return 0;
}
程序运行后结果为:7.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐