高效求一个整数中1的位数

求一个整数中0或1的位数,有很多方法可以使用除法,求余等方法,也可以使用位运算,相比前者效率更高。

#include <stdio.h>

#include <stdlib.h>

//求一个整数 1的位数

int count0(int x)

{

    int num=0;

    while(x)

    {

        num+=x%2;

        x/=2;

    }

    return num;

}



int count1(int x)

{

    int num=0;

    while(x)

    {

        num+=(x&0x01);

        x>>=1;

    }

    return num;

}



int count2(int x)

{

    int num=0;

    while(x)

    {

        x &=(x-1);

        num++;

    }

    return num;

}

int main()

{

    unsigned int x=10;

    printf("%d   %d\n",x,count0(x));

    printf("%d   %d\n",x,count1(x));

    printf("%d   %d\n",x,count2(x));

    return 0;

}

  

 

你可能感兴趣的:(高效求一个整数中1的位数)