求任意一个正整数的二进制中有多少个比特位为1

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q1075355798/article/details/79830231

思路

一个正整数的二进制中有多少个比特位为1,最直接可想到的是,将该正整数化为二进制的形式,挨个数出其中有多少个1即可。C语言中,和比特位相关的内容,即是位操作。此处可以将该正整数与 0x01 进行位与,即可得知该数的二进制最低位是否为1,然后将该数向右移动一位,再次判断移动后的最低位是否为1,依次操作,直到该数右移变成0.

代码实现

#include <stdio.h>

static void count(int number)
{
    int cnt = 0;
    int num = number;
    if (num < 0)
        return;
    do {
        if (num & 0x01 == 1) 
            cnt++;  
    } while((num >>= 1) != 0);

    printf("there are %d one in %d of the binary\n",cnt, number);
    return; 
}

int main(void)
{
    count(2);
    count(5);
    count(30);
    count(32);
    count(34);
    count(36);
    count(38);
    count(39);
    count(40);
    return 0;
}

运行结果

./a.out
there are 1 one in 2 of the binary
there are 2 one in 5 of the binary
there are 4 one in 30 of the binary
there are 1 one in 32 of the binary
there are 2 one in 34 of the binary
there are 2 one in 36 of the binary
there are 3 one in 38 of the binary
there are 4 one in 39 of the binary
there are 2 one in 40 of the binary

注意

此处为何要强调是正整数?因为负数在计算机中的存储方式是以补码形式存在的。需要特别的处理。那么,假设该题变为:求任意一个负整数中有多少个比特位为1,又该怎么处理呢?
此时,看对该问题怎么理解,如果是按照正整数那样,求原码中有多少个比特位为1,那可以根据负数原码的特点:其原码最高位为1,表示负数,其他位的数值,与该负数绝对值所对应的整数一样,比如在32位机器上,+1 的原码是 0000 0000 0000 0000 0000 0000 0000 0001,则 -1 的原码是 1000 0000 0000 0000 0000 0000 0000 0001。那么此时,要求 -1 的原码中有多少个比特位为1,思路是先求 -1 的绝对值中有多少个比特位为1,最后再加上最高位的符号位1即可。

#include <stdio.h>
#include <stdlib.h>

static void count(int number)
{
    int cnt = 0;
    int num = abs(number);
    do {
        if (num & 0x01 == 1) 
            cnt++;  
    } while((num >>= 1) != 0);
    if (number < 0)
        cnt += 1;

    printf("there are %d one in %d of the binary\n",cnt, number);
    return; 
}

int main(void)
{
    count(2);
    count(-2);
    return 0;
}

运行结果:
./a.out
there are 1 one in 2 of the binary
there are 2 one in -2 of the binary

猜你喜欢

转载自blog.csdn.net/q1075355798/article/details/79830231