转载-求一个数转换成为二进制中1的个数

转载自:求一个数转换为二进制中1的个数

 

// Count1--01.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

int coutn1(int num)
{
    int result = 0;
    while (num)
    {
        result+=num&0x01;//如果是1的话,整个个数加1,如果是0的话,那么就是+0;这样就可以知道二进制中1的个数了
        num>>=1;
    }
    return result;
}
int coutn102(int num)//编程之美上面介绍的很好的方法
{
    int result=0;
    while (num)
    {
        num&=(num-1);
        result++;
    }
    return result;
}


int _tmain(int argc, _TCHAR* argv[])
{
    cout<<coutn1(10000)<<endl;
    cout<<coutn1(10000)<<endl;

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/lwflourish/p/4494794.html