Find the number of 1's in an integer

Idea 1: Judging by the method of remainder

 
 
#include<stdio.h>
intmain()
{
     int a=0;
     int i=0,count=0;
     printf("Please enter a positive integer: "); 
     scanf("%d",&a); 
     do 
     {
         if((a%2)==1)
         {
            count++;
            a/=2;
         }
    }while(a);
    printf("Number of 1s in binary in this positive integer:%d\n",count); 
    return 0;
}
Defect: Negative numbers cannot be processed. Negative numbers are stored in memory in the form of complement. In the complement of negative numbers, the first bit is 1 to represent the negative sign, so in the above loop, no matter how many loops are looped, it cannot be 0. The program infinite loop
It is a negative number before shifting, and it is still necessary to ensure that it is a negative number after shifting, so the highest bit will be set to 1 after shifting. If you keep doing right shifts, eventually the number will become
0xFFFFFFFF and fall into an infinite loop.

Idea 2: By bit manipulation and right shift operator

 
 

#include<stdio.h>
intmain()
{
   int a=0;
   int i=0,count=0;

   printf("Please enter a positive integer:")
   scanf("%d",&a);
   for(i=0;i<32;i++)// An integer occupies four bytes, and one byte is eight bits, so you need to loop 32
   {
       if((a>>i)&1==1)
       {
           count++;
       }
   }
   printf("Number of 1's in binary in this integer:%d\n",count);
   return 0;
}
Get the number of 1s in a binary number by controlling 1
#include<stdio.h>
int main()
{
   int a=0;
   int i=1,count=0,j=0;
   printf("Please enter a positive integer:");
   scanf("%d",&a );
   while(i)
   {
    if (a&i)
    {
     count++;
    }
    i = i << 1;
   }
   printf("Number of 1's in the integer:%d\n",count);
   return 0;
}


Idea 3: By ANDing itself minus 1
 
 
#include<stdio.h>
intmain()
{
   int a=0;
   int i=0,count=0;
   printf("Please enter a positive integer:")     
   scanf("%d",&a);
   while(a)
   {
         a&=(a-1);
         count++;
   }
   printf("Number of 1's in binary in this integer:%d\n",count);
   return 0;
}



Guess you like

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