Pretty good way to check if a number is a power of two or not.
'states if a number is a power of two'
return num != 0 and ((num & (num - 1)) == 0)
Nice. Somebody might prefer it spelled as "return num and not num & (num - 1)".
i'm happy you like it ;)
@matteo of course..but i think it's a little bit clearer in this way :)
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
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
How does this work? That's pretty cool.
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...
| Contact Us
© 2021 ActiveState Software Inc. All rights reserved.
ActiveState®, Komodo®, ActiveState Perl Dev Kit®,
ActiveState Tcl Dev Kit®, ActivePerl®, ActivePython®,
and ActiveTcl® are registered trademarks of ActiveState.
All other marks are property of their respective owners.