查找输入整数二进制中1的个数(HJ62)

一:解题思路

这道题目和 leetcode 191 一样的,可以放在一起学习。

二:完整代码示例 (C++版和Java版)

C++:

#include <iostream>

using namespace std;

int theNumberOfOne(int n)
{
    int counts = 0;

    while (n != 0)
    {
        counts++;
        n &= (n-1);
    }

    return counts;
}

int main()
{
    int n = 0;

    while (cin >> n)
    {
        cout << theNumberOfOne(n) << endl;
    }

    return 0;
}

 

posted @ 2020-08-03 12:07  repinkply  阅读(284)  评论(0)    收藏  举报