【小技巧】统计二进制数1的个数

移位计数

依次判断每一位上是不是1


int fun(int x)//求二进制1的个数
{
    int res=0;
    while(x)
    {
        if(x&1)//当前位为1
            res++;
        x>>1;
    }
    return res;
}

更快速的方法

每次循环不断清除最右边的1,直到该数为0为止。

int fun(int x)
{
    int res =0 ;
    while(x)
    {
        x&=(x-1) ; // 清除最低位的1
        res++;
    }
    return res;
}

猜你喜欢

转载自blog.csdn.net/cqbzlytina/article/details/79387546
今日推荐