求十进制数转化成二进制后包含1的个数

#include <iostream>
using namespace std;

int func(int x) //函数的关键代码
{
    int count=0;
    while(x)
    {
        x=x&(x-1);
        count++;
    }
    return count;
}

int main()
{
    cout<<func(9999)<<endl;
    return 0;
}

输出结果为8

我的个人博客网站:www.ihunter.me

posted @ 2013-07-02 15:13  hunterzhang  阅读(231)  评论(0编辑  收藏  举报