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: Crazy Google Interview Ques... | Psycho Killer | Bricks |

Discussion

comments with spoilers hidden | Show All
eljobe 5 months ago contains spoiler (show)
m8rsh 5 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 5 months ago contains spoiler (show)
graylocke 5 months ago contains spoiler (show)
avinash 5 months ago contains spoiler (show)
gmiller 5 months ago contains spoiler (show)
gmiller 5 months ago contains spoiler (show)
axman6 5 months ago contains spoiler (show)
turtlesoft 6 months ago contains spoiler (show)
jeffl 6 months ago contains spoiler (show)
valentin 6 months ago contains spoiler (show)
johnp 6 months ago

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

city_slick 6 months ago

yes, very interesting..

kash 6 months ago

I like this one..pretty tricky.