Skip to content Skip to sidebar Skip to footer

Check If Two Integers Have The Same Sign

I'm searching for an efficient way to check if two numbers have the same sign. Basically I'm searching for a more elegant way than this: var n1 = 1; var n2 = -1; ( (n1 > 0 &

Solution 1:

You can multiply them together; if they have the same sign, the result will be positive.

bool sameSign = (n1 * n2) > 0

Solution 2:

Fewer characters of code, but might overflow:

n1*n2 > 0 ? console.log("equal sign") : console.log("different sign or zero");

or without integer overflow, but slightly larger:

(n1>0) == (n2>0) ? console.log("equal sign") : console.log("different sign");

if you consider 0 as positive the > should be replaced with <

Solution 3:

Solution 4:

That based on how you define "same sign" for special values:

  • does NaN, NaN have the same sign?

If your answer is "No", the answer is:

Math.sign(a) === Math.sign(b)

If your answer is "Yes", the answer is:

Object.is(Math.sign(a) + 0, Math.sign(b) + 0)

Solution 5:

n = n1*n2;
if(n>0){ same sign}else{ different sign}

Post a Comment for "Check If Two Integers Have The Same Sign"