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

Sign uporlog in with Facebookto comment.Vishal barotjust mod by 2 and ans should be 0

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