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.
(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.
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
By Robin on 02.01.07 2:39 pm | Permalink
This will be 0 if only one bit.
otherwise, it is non-zero.
By Robin on 02.01.07 2:40 pm | Permalink
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.
By Toddsa on 03.04.07 4:14 pm | Permalink
Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.