这个问题有好多种解法,下面给出C++实现的一种(通过测试),其余方法及对比请参考:http://blog.sina.com.cn/s/blog_63ce05ca0100u0ft.html
#include<iostream>
using namespace std;
int main()
{
int n,m=0;
cin>>n;
unsigned int flag=1;
while(flag)
{
if(n&flag)
m++;
flag=flag<<1;
}
cout<<m<<endl;
//system("pause");
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int n,m=0;
cin>>n;
while(n)
{
if(n&1)
m++;
n=n>>1;
}
cout<<m<<endl;
//system("pause");
return 0;
}