一共有三种方法实现,具体看下面
第一种
int count1(int v)
{
int num=0;
while (v)
{
if(v%2 ==1)
num++;
v/=2;
}
return num;
}
第二种
int count2(int v)
{
int num=0;
while (v)
{
num+=v & 0x01;
v>>=1;
}
return num;
}
第三种
int count3(int v)
{
int num=0;
while (v)
{
v&=(v-1);// 执行一次之后,v减1;知道v为0
num++;
}
return num;
}
测试程序
#include <iostream>
using namespace std;
int main()
{
int count_i_1,count_i_2,count_i_3;
int i=1,x;
while(i)
{
cin>>x;
cout<<"中1的个数是: ";
count_i_1=count1(x);
count_i_2=count2(x);
count_i_3=count3(x);
cout<<count_i_1<<"个 "<<count_i_2<<"个 "<<count_i_3<<"个"<<endl;
i=x;
}
return 0;
}