2fas7g
Last Updated: February 25, 2016
·
1.312K
· tripples
35619bacc47ad73326472281767fae7e

Check if number power of 2

Recently I found this simple one liner which can save your time & can be efficient
to check if number is power of 2.

a = some int
if ( a & (a - 1)):
    print "Num not power of 2"
else:
    print "Number power of 2"
Say Thanks
Respond

4 Responses
Add your response

7871
8913637bf54bf7d3346f47e026489adf

I'm sorry, I may be mistaken but isn't it the opposite?
E.g :

8 -> 1000
7 -> 0111
& -> 0000

But 8 do is a power of 2 and a & (a - 1) == false in this very case.

over 1 year ago ·
7872
35619bacc47ad73326472281767fae7e

Thankx for pointing it out. I written that in hurry, so made a mistake. I have updated tip.
In case of 8 ,
a & (a - 1) == false
So number is power of 2.

1 )For false == number is power of 2
2) For true == number is not power of 2

over 1 year ago ·
8020
Profile

Alternately, you could simply do:
!(a & 1)
if you're concerned about efficiency, you have one less operation (the a-1).

over 1 year ago ·
18684
None

!(a&1) will tell wheather the number is even or not..But we need if it is power of 2.

over 1 year ago ·