Thursday 18 July 2013

Challenging C Questions

1. How to count no of bits set in a no.
    eg. it should be 2 for 5(0101).


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


2. To check if no is power of 2.

Sol.
if (x!=0)
if(!(x&(x-1)))
printf("\n No is power of two");