HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Checking if two numbers have the same sign

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethenumberscheckingtwosignhave

Problem

Is there a more elegant way than the following to check if two numbers have the same sign?

bool sameSign(int num1, int num2)
    {
        if (num1 > 0 && num2  0)
            return false;
        return true;
    }


It could also be written as the not case of all of this (e.g. check the true cases and return false at the end).

By design, the two integers will never contain a zero value.

Solution

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

Code Snippets

bool sameSign(int num1, int num2)
{
    if (num1 > 0 && num2 < 0)
        return false;
    if (num1 < 0 && num2 > 0)
        return false;
    return true;
}
bool sameSign(int num1, int num2)
{
    return num1 >= 0 && num2 >= 0 || num1 < 0 && num2 < 0
}
return (num1 ^ num2) >= 0

Context

StackExchange Code Review Q#107635, answer score: 66

Revisions (0)

No revisions yet.