Welcome, guest | Sign In | My Account | Store | Cart

Pretty good way to check if a number is a power of two or not.

Python, 7 lines
 ```1 2 3 4 5 6 7``` ```#Author: A.Polino def is_power2(num): 'states if a number is a power of two' return num != 0 and ((num & (num - 1)) == 0) ```

Matteo Dell'Amico 10 years, 11 months ago

Nice. Somebody might prefer it spelled as "return num and not num & (num - 1)".

A. Polino (author) 10 years, 11 months ago

i'm happy you like it ;)

@matteo of course..but i think it's a little bit clearer in this way :)

david.gaarenstroom 10 years, 11 months ago

If you want to do it even better, use this:

``````return ((num & (num - 1)) == 0) and num != 0
``````

Which saves one check in most cases, since the check for 0 is only necessary if the other one evaluates to true... Also, you might want to check for a positive value, so this is probably better:

``````return ((num & (num - 1)) == 0) and num > 0
``````
A. Polino (author) 10 years, 11 months ago

you're right in the first sample (but it's really premature optimization)

in the second you're wrong; if you want to save the check for num <= 0 you should write

``````return num > 0 and ((num & (num - 1))
``````

otherwise, 'num > 0' will never be executed unless num == 0

Sunjay Varma 10 years, 11 months ago

How does this work? That's pretty cool.

david.gaarenstroom 10 years, 11 months ago

Premature optimization is when you try to enhance your code before it actually works properly, in this case it's plain math.

And no, I am assuming you are using this function judiciously and aren't usually feeding it with illegal input (negative numbers), so it is really just a fall-back, so you can still best put it at last, but it does make less difference. But you are being a bit blunt calling me "wrong" here. If you are feeding it with random data, you should perhaps also check you are using integer input...

 Created by A. Polino on Thu, 23 Dec 2010 (MIT)

Required Modules

• (none specified)