将一个数转化为二进制后,求其中1的个数 C++

#include <iostream>
using namespace std;
int func(int x)
{
int count=0;
while(x)
{
x=x&(x-1);//与的次数就是包含1的个数
count++;
}
return count;
}

void main()
{
int x;
cin>>x;
cout<<func(x)<<endl;
}

posted @ 2015-04-25 14:56  默默成长  阅读(299)  评论(1编辑  收藏  举报