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



思路一:一个数取模的结果就是最低比特位,如果取模是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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值