Log in! (forgot password)
Power of 2 (Microsoft Interview)
Given any number n, using one line of C (using no external libraries or functions) code, determine if n is a power of 2. Return 1 if n is a power of 2 and 0 if not.
Discussion
ho this was for a multiple.
the answer given is almost correct but it is in fact:
(n & ~ (n – 1))
int getPair(int nb) {
return (nb & ~ 1);
}
The answer is false.
Consider 2, which is a power of 2. When stored as a 32-bit int, it is encoded as:
0000 0000 0000 0000 0000 0000 0000 0010
n – 1 is
0000 0000 0000 0000 0000 0000 0000 0001
bitwise and
0000 0000 0000 0000 0000 0000 0000 0011
logical negation
0
bitwise negation would give a non-zero answer, but it would give a non-zero answer for any number less than 2^33-1 (all but 32 1s in a row).
well…i’m glad i’m not a computer scientist…
yes, very interesting..
I like this one..pretty tricky.
Difficulty
Currently: Moderate (5.29)
