## Sunday, July 8, 2007

### Write C code to check if an integer is a power of 2 or not in a single line?

Even this is one of the most frequently asked interview questions. I really dont know whats so great in it. Nevertheless, here is a C program

Method1

if(!(num & (num - 1)) && num)
{
// Power of 2!
}

Method2

if(((~i+1)&i)==i)
{
//Power of 2!
}

I leave it up to you to find out how these statements work.

Rani said...

we can do it as

int findpower(unsigned char x)
{
return !((x-1)&x)
}

if its true then its power of 2 else its not....

Anonymous said...

if((double)((int)(log(n)*1.0/log(2))) == (log(n)*1.0/log(2)))
{
// power of 2
}

Anonymous said...

above should be good for any power-of number, not just 2

Anonymous said...

Is this possible?

Anonymous said...

I give u best solution.
Logic- when u convert a decimal number to its binary number then u get series of 1 and 0
Now if a number is power of two then u will observe it has only one (bit 1) and it u do binary anding of ot it with just a number previous to it ,then u will get Zeros
For example
8=1000(binary form ) here u can see only one (bit 1) is there rest are zeros
Now the number just previous to 8 is 7
so, 7=0111 and if u perform anding operation on it as
1000(8)
(AND) 0111(7)
---------
0000(0)
---------
So if we perform AND operation between the number (which we want to check is a power of two or not) and the number just previous to it and result comes as zeros then its power of two otherwise it s not.
PROGRAM(IN C_LANGUAGE)
#include
#include
main()
{
int num, num1,sum;
clrscr();
printf("Enter the number");
scanf("%d",&num);
printf("\nEntered number=%d",num);
num1=num-1;
sum=num & num1;
if(sum==0)
printf("\n Entered number is power of two");
else
printf("\n Entered number is not power of two");
getch();

Cindy Dy said...

Hey there! Someone in my Myspace group shared this website with us so I came to check it out.I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers!Terrific blog and fantastic design and style.

Bubble
www.gofastek.com

Silvia Jacinto said...

Mistake does not only teach you how to be strong but also how to stand up again and to do good next time. Visit my site for more information. Have a good day always and thank you for sharing your knowledge and wonderful article to the public. I do hope that you can inspire more readers.

n8fan.net

www.n8fan.net

Nicholas Watkins said...

This really answered my problem, thanks! gsn casino slots