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"
Written by Sanket Sudake
Related protips
3 Responses
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
·
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
·
!(a&1) will tell wheather the number is even or not..But we need if it is power of 2.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#