Sunday, December 3, 2006

Most efficient way to count no of 1's in a no.

Basic method 

int CountBits(unsigned int x)
  {
      int count=0;
      while(n)
      {
          if(n%2)
           count++;
          n=n/2 ; // n>>1
      }
      return count;
  }
 
Efficient


int CountBits(unsigned int x)
 {
   int count=0;
   while(x)
   {
     count++;
     x = x&(x-1);
   }
   return count;
 }

Other methods

int showBinarynCount(int no)
{

       int noofOnes = no%2;
      if(no)
     {
       noofOnes = noofOnes + showBinarynCount(no/2) ; // showBinarynCount(no>>1)
      
printf("%d",no%2) ;
    }
  return noofOnes ;
}







  int CountBits(unsigned int x)
  {
      int count=0;
      while(x)
      {
          count++;
          x = x&(x-1);
      }
      return count;
  }

---------------------------
int CountBits (unsigned int x )
{
x = (x & 0x55555555) + ((x>>1) & 0x55555555);
x = (x & 0x33333333) + ((x>>2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x>>4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x>>8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x>>16) & 0x0000FFFF);
return x;
}