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:
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...
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:
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:
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
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...