计算一个整数的二进制表达中1的个数

count_one.cpp内容如下:

#include <iostream>
using namespace std;

int count_one(int n)
{
    int count = 0;
    while (n)
    {
        n = n & (n - 1);
        ++count;
    }
    return count;
}

int main(int argc, char **argv)
{
    const int kRange = 20;
    for (int i = 0; i < kRange; ++i)
        cout << i << " has " << count_one(i) << " 1's in its binary representation." << endl;

    return 0;
}

运行结果如下图所示:

posted @ 2020-07-29 14:01  jackie_astro  阅读(148)  评论(0编辑  收藏  举报