欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

求一个整数存储在内存中的二进制中1的个数

程序员文章站 2022-07-15 09:49:53
...

方法1 :

一个10进制的数123 得到它的每一位%10

123/10=12...3

123%10=3

 

12/10=1...2

12%10=2

 

1/10=0...1

1%10=1

 

一个2进制的数 得到它的每一位 %2

3

011

 

3/2=1...1

3%2=1

 

1/2=0...1

1%2=1

int main()

{

        int num = 0;

        int count = 0;

        scanf("%d", &num);

        //统计num中的补码中有几个1

        while (num)

        {

               if (num % 2 == 1)

                       count++;

               num = num / 2;

        }

        printf("%d\n", count);

        return 0;

}

缺点:当num=-1时有问题

 

方法2  :

一个整形4个字节-32bit

3:     00000000 00000000 00000000 000000011

1:     00000000 00000000 00000000 000000001

3&1: 00000000 00000000 00000000 000000001

 

3>>1        00000000 00000000 00000000 000000001

1:           00000000 00000000 00000000 000000001

3>>1&1:00000000 00000000 00000000 000000001

int main()

{

        int num = 0;

        int count = 0;

        scanf("%d", &num);

        int i = 0;

        for (i = 0; i < 32;i++)

        {

               if (1 == ((num >> i) & 1))

                       count++;

        }

        printf("%d\n", count);

        return 0;

}

缺点:必须循环32次

 

方法3:

int main()

{

        int num = 0;

        int count = 0;

        scanf("%d", &num);

        while (num)

        {

               count++;

               num = num&(num - 1);

        }

        printf("%d\n", count);

        return 0;

}

 

相关标签: C c语言