计算一个数字的二进制中1的个数

计算一个数字的二进制中1的个数
法一

int main()
{
    int n;
    cin >> n;
    int count = 0;
    while (n)
    {
        if (n & 1 == 1)
        {
            count++;
        }
        n = (n >> 1);
    }
    cout << count << endl;
    system("pause");
}

法二 较优解法:

#include<iostream>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int count = 0;
    while (n)
    {
        n = n&(n - 1);
        count++;
    }
    cout << count << endl;
    system("pause");
}
posted @ 2017-03-16 18:53  乐天的java  阅读(51)  评论(0)    收藏  举报