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.


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:

Like this? You might also like:
Time To Fuse
Farmer's Market
Interview Question - Databases
Submitted by
over 4 years ago
Difficulty 6.0 ?

bitwise powers