Log in! (forgot password)
Username: Password:
Back Bricks Random ??? Next Tea and Wine
All Puzzles / Computer Science /

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.

Bookmark and Share
(Show)
(Show)
People who liked this also liked: The Classic Weights & Scale | Prisoners and hats | What am I? |

Discussion

comments with spoilers hidden | Show All
folcklord about 22 hours ago
folcklord 11 days ago
phentermine 425 cialis dpzpzp buy tramadol 295 cialis :-DDD
kaervas 2 months ago

ho this was for a multiple.
the answer given is almost correct but it is in fact:
(n & ~ (n – 1))

kaervas 2 months ago

int getPair(int nb) {
return (nb & ~ 1);
}

eljobe 10 months ago contains spoiler (show)
m8rsh 11 months ago

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

graylocke 11 months ago contains spoiler (show)
graylocke 11 months ago contains spoiler (show)
avinash 11 months ago contains spoiler (show)
gmiller 11 months ago contains spoiler (show)
gmiller 11 months ago contains spoiler (show)
axman6 11 months ago contains spoiler (show)
turtlesoft 11 months ago contains spoiler (show)
jeffl 11 months ago contains spoiler (show)
valentin 11 months ago contains spoiler (show)
johnp 11 months ago

well…i’m glad i’m not a computer scientist…

city_slick 11 months ago

yes, very interesting..

kash 11 months ago

I like this one..pretty tricky.