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


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


//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...

I would like to exchange links with your site
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
(AND) 0111(7)
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.
int num, num1,sum;
printf("Enter the number");
printf("\nEntered number=%d",num);
sum=num & num1;
printf("\n Entered number is power of two");
printf("\n Entered number is not power of two");

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.


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.

Nicholas Watkins said...

This really answered my problem, thanks! gsn casino slots