First up, your code has bugs. What if one of the numbers is 0? 0 should be positive, but your code treats it as negative in some tests, and positive in others. When comparing against 0 you should use >=
, not just >
.
The actual code is quite readable, though, and the performance is probably not horrible. I would recommend a single return statement though. A single return statement is easier if you check for "the same sign", and not "opposite signs".
Take your code:
bool sameSign(int num1, int num2)
{
if (num1 > 0 && num2 < 0)
return false;
if (num1 < 0 && num2 > 0)
return false;
return true;
}
Fix the 0-handling, and you have:
bool sameSign(int num1, int num2)
{
return num1 >= 0 && num2 >= 0 || num1 < 0 && num2 < 0
}
Now, that's pretty good, and I would happily "pass" that in a code review, but, can you do some tricks?
The simplest (code wise) is to use XOR:
return (num1 ^ num2) >= 0
That compares the bits, and if they are the same, it sets the resulting bit to 0. If the sign bits are the same, the resulting sign-bit is 0, and thus a positive (or 0) value.