Time spent here:

Tuesday, 22 December 2015

Check if a given number is sparse or not

A number is said to be a sparse number if in binary representation of the number no two or more consecutive bits are set. Write a function to check if a given number is Sparse or not.
consider x=3
binary form of 3 is 0011
step 1:right shift 'x'  then 0001 
step 2:do AND product
             0011
             0001
            ----------
             0001
           ----------
step3:
          if     
              the answer is 0 then it is sparse number
         else
              it is not a sparse number 
CODE:
#include <stdio.h>

int main()
{
   int x;
   scanf("%d",&x);
   if(x & (x >> 1))
       printf("not sparse");
   else
       printf("sparse");
    return 0;

}

No comments:

Post a Comment