位运算题

bitcount函数 计算出正整型x中位为1的个数。

int bitcount(unsigned int x){
    int res;
    for (res=0;x!=0;x>>=1)
    {
        if(x&1) res++;
    }
    return res;
}

//利用 表达式x&=(x-1)可以去掉x最右边值为1的二进制位。
int bitcount_version2(unsigned int x){
    int res;
    for (res=0;x!=0;x&=(x-1))
    {
        res++;
    }
    return res;
}
原文地址:https://www.cnblogs.com/fightformylife/p/4315726.html