版权声明:转载请注明出处。 https://blog.csdn.net/u014427196/article/details/40650997

int BitCount(unsigned int n)
{
    unsigned int c =0 ; // 计数器
    while (n >0)
    {
        if((n &1) ==1) // 当前位是1
            ++c ; // 计数器加1
        n >>=1 ; // 移位
    }
    return c ;
}

2. 快速移位+计数

int BitCount2(unsigned int n)
{
    unsigned int c =0 ;
    while(n)

  {
        n &= (n -1) ;

        c++;// 清除最低位的1
    }
    return c ;
}