Log in! (forgot password)
All Puzzles / Computer Science /
(Show)
(Show)
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
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).
turtlesoft 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.
❤ Join MindCipher!
You'll be able to comment on, rate, like, and add puzzles; and be part of our community!
13 likes
Difficulty
Currently: Moderate (5.0)
