This site features a collection of common technical interview questions gathered by a group of programmers who have been through, and given, lots of technical interviews. There is an emphasis on C++ and game programming technical interviews, but most of the questions are relevant to any technical interview.
I’ve Got the Power (of 2)

Write a C function to test whether a number is a power of 2. Try to do it without using any loops.


3 Comments so far
Leave a comment

I could not put in the leftshit operator.

Answer is:

X leftshift by 1 bit &
X leftshift by 2 bits &
X leftshift by 3 bits

This will be 0 if only one bit.
otherwise, it is non-zero.

given x as an integer

(x & (x-1)) will be 0 if x is a power of 2 and non zero if it is not. The reason is all power of 2’s in binary will have a single set bit and (x-1) will have all set bits excluding x. for example x = 8 in binary is 1000 and (x-1) or 7 in binary is 111 so if you use the & operator you will get.

1000
& 0111
——
0000

Any x this is not a power of 2 will result in some other non 0 result.



Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.


Do you have a technical interview question you would like to submit? Some tips you would like to pass on? Just want to say hi? Feel free to contact us