Welcome to MindCipher, a social repository of the world's greatest brain teasers, logic puzzles and mental challenges.

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.

see explanation

bool is_power_of_2 = (!(n & (n-1)) && n);

Using the bitwise & operator, only n’s that are powers of two will satisfy the relationship n & (n-1) = 0. This, however incorrectly returns 0 as a power of 2. n must be strictly positive for this to work. To fix this we use !(n & (n-1)) && n.

Comments


Vishal barot

just mod by 2 and ans should be 0

  

Nigel Parsons

Mod2 will give zero for any even number, not just powers of 2.

Check out other puzzles:
Random  

Like this? You might also like:
Don't be a Square
Lab Rat on the Run
Matchsticks
Submitted by
Aakash
almost 5 years ago
Likes
Difficulty 6.0 ?

Tags
bitwise powers


Back