位运算题

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;
}

 

posted @ 2015-03-05 14:16  雄哼哼  阅读(197)  评论(0编辑  收藏  举报