2fas7g
Last Updated: February 25, 2016
·
3.52K
· tripples

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"

4 Responses
Add your response

7871

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

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

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

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

over 1 year ago ·