输入一个整数,统计并输出它二进制中有多少个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;
}