Find the number of "1" in binary

Topic description: For an unsigned integer variable of one byte (8 bits), the number of "1" in the binary representation requires that the execution efficiency of the algorithm be as high as possible.

  • Method 1
    Idea: First of all, a better method is to think of >> and & on binary numbers, so that the number of "1" in the sequence can be gradually found. (Note: 1&1=1, 1&0=0, 0&0=0)
int Count(int num)
{
    int count = 0;
    while (num)
    {
        count += (num & 0x01 );
        num >>= 1;
    }
    return count;
}


  • Method 2
    Ideas: For a binary number, the first time you divide it by 2, the original number will be reduced by a 0. If there is more than one, it means that there is a 1 in the current position.

For example: the first division of 1010 0010
by 2, the quotient is 1010001, and the remainder is 0;
the second division by 2, the quotient is 101000, and the remainder is 1.
int Count(int num)
{
    int count = 0;
    while (num)
    {
        if (num % 2 == 1)
            count++;
        num /= 2;        //同num >>= 1;
    }
    return count;
}
  • Method 3
    Ideas: The efficiency of bit operations is higher than that of division and remainder operations. The third method is also an ingenious method.
int Count(int num)
{
    int count = 0;
    while (num)
    {
        num &= (num - 1);
        count++;
    } 
    return count;
}
  • test code
int main()
{
    int i = 9;
    int N = 0;
    N = Count(i);
    printf("%d\n", N);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325847621&siteId=291194637