Sunday, February 10, 2013

Program to check the given number is power of two or not?

/*
Program to check the given number is power of two

*/


#include<stdio.h>
void main()
{
    int num,exor;
    printf("Enter a number:\n");
    scanf("%d",&num);
    exor=num & (num-1);
    if(exor==0)
        printf("Number is pow of 2\n");
    else
        printf("Number is not pow of 2\n");   
}


/*
Simple logic
Step 1:just read the number
Step 2:find Exclusive OR of number and (number-1) assign value to some variable say exor
Step 3: if exor's value is zero (0) thn we say number is the power of 2 otherwise not


If not understood convert the number and (number-1) to binary and follow from step 2
*/

No comments:

Post a Comment