**Question:** How do you find out if an unsigned integer is a power of 2?

**Answer:** The trick here is to know that an unsigned integer which is a power of 2 has only one of its bits as 1. So a simple solution would be to loop through the bits and count the number of 1s.

There is another solution which uses bit manipulation.

isPower = (x !=0 && !(x & (x-1)))

x & (x-1) will always give you a 0 if x is a power of 2. !(x & (x-1)) should give us what we want but there is one corner case. If x is 0, then the second term alone would return true when the answer should be false. We need the check to make sure x is not 0.

Most interviewers would be happy with the first solution. The second solution might be quite hard to come up with on the spot unless of course you are a genius or you have read the solution before.

If you have any questions, please feel free to send me an email at support@mytechinterviews.com. If you have any interview questions which you feel would benefit others, I would love to hear about it.

Easy way to find whether a number is power of 2.

/*

* A program to find whether a given number is a power of 2.

* jagannath_pattar@yahoo.co.in

*/

#include

void power_of_2(int num)

{

num = num & num-1;

if(num)

printf(“\nNumber is not power of 2\n”);

else

printf(“\nNumber is power of 2\n”);

}

main()

{

unsigned int num;

printf(“Enter the number: “);

scanf(“%d”, &num);

power_of_2(num);

}