[置顶] 写一个函数返回参数二进制中1的个数

时间:2023-02-13 20:58:57


写一个函数返回参数二进制中1的个数://15--00001111//

方法一:

#include<stdio.h>

#include<stdlib.h>

int main()

{

        for(;;){

        inta,b,i,count=0;

        printf("请输入一个数字:");

   scanf("%d",&a);

        while(a){

                  b=a/2;

                  i=a%2;

                  a=b;

                  if(i==1)

                  {

                           count++;

                  }

        }

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

        }

        system("pause");

        return0;

 

}

//此方法不能计算<0的情况//

[置顶]        写一个函数返回参数二进制中1的个数

 

 

 

2.方法二:

#include<stdio.h>

#include<stdlib.h>

int main()

{

        intnum =15;

        intcount=0;

        while(num)

                  {

                                    if(num%2==1)

                                 count++;

                                    num=num/2;

                  }

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

       system("pause");

            return 0;

 

}

 

[置顶]        写一个函数返回参数二进制中1的个数

方法三:

#include<stdio.h>

#include<stdlib.h>

int main()

{

        intnum =15;

        intcount=0;

        inti=0;

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

        {

           if(num&1==1)

                           count++;

                      num=num>>1;

                  }

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

       system("pause");

            return 0;

 

}

//此处<<表示左移一位,此时像右边补一个0>>表示右移一位,此时像左边补一个符号位//

[置顶]        写一个函数返回参数二进制中1的个数