用C++实现统计二进制中1的个数

 输入一个整数,统计并输出它二进制中有多少个1
 例如输入123456789
 二进制(111010110111100110100010101) 2
 输出结果为16

法1:

#include<iostream>
#include<cmath> 
using namespace std;
int main()
{
	int a,b,c,n;
	unsigned long long int i;
		i=0;
		n=0;
		c=0;
		cout<<"请输入一个整数:";
		cin>>a;
		cout<<"整数"<<a;
		while(a!=0)
		{
			b=a%2;//a对2取余 
			a=a>>1;//a左移一位 
			if(b==1)
			{
				c++;
			}
			i=i+b*pow(10,n);//转换为二进制 
			n++;
		}
		cout<<"的二进制为:"<<i<<endl;
		cout<<"该数二进制中1的个数为:"<<c; 
	    return 0;	 
}	

法2 

#include<iostream>
#include<cmath> 
using namespace std;
int main()
{
	int a[16]={0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
	unsigned int n,i;
	cout<<"请输入一个整数:";	
	cin>>n;
	int b=0;
	for(i=1;i<=7;i++)
	{
		b=b+a[n&0xf];
		n=n>>4;//左移4位 
	}
    cout<<"该数二进制中1的个数为:"<<b; 
	return 0;
}

法3 

#include<iostream>
using namespace std;
int main()
{
	unsigned int n;
	cout<<"请输入一个整数:";
	cin>>n;
	n = (n&0x55555555) + ((n>>1)&0x55555555);  //01010101010101010101010101010101
	n = (n&0x33333333) + ((n>>2)&0x33333333);  //00110011001100110011001100110011
	n = (n&0x0f0f0f0f) + ((n>>4)&0x0f0f0f0f);  //00001111000011110000111100001111
	n = (n&0x00ff00ff) + ((n>>8)&0x00ff00ff);  //00000000111111110000000011111111
	n = (n&0x0000ffff) + ((n>>16)&0x0000ffff); //00000000000000001111111111111111
	cout<<"该数二进制中1的个数为:"<<n; 
	return 0;
}

法4 

#include<iostream>
using namespace std;
int main()
{
	unsigned int n;
	cout<<"请输入一个整数:";
	cin>>n;
	int a=0;
	while(n>0)
	{
		n=n&(n-1);
		a++;
	}
    cout<<"该数二进制中1的个数为:"<<a; 
	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值