'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 && n2 > 0) || (n1<0 && n2 < 0) )? console.log("equal sign"):console.log("different sign");
A solution with bitwise operators would be fine too.
Solution 1:[1]
Fewer characters of code, but might underflow for very small numbers:
n1*n2 > 0 ? console.log("equal sign") : console.log("different sign or zero");
Note: As @tsh correctly mentioned, an overflow with an intermediate result of Infinity
or -Infinity
does work. But an underflow with an intermediate result of +0
or -0
will fail, because +0
is not bigger than 0
.
or without underflow, but slightly larger:
(n1<0) == (n2<0) ? console.log("equal sign") : console.log("different sign");
Solution 2:[2]
You can multiply them together; if they have the same sign, the result will be positive.
bool sameSign = (n1 * n2) > 0
Solution 3:[3]
Use bitwise xor
n1^n2 >= 0 ? console.log("equal sign") : console.log("different sign");
Solution 4:[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:[5]
n = n1*n2;
if(n>0){ same sign }
else { different sign }
Solution 6:[6]
Simple easy:
bool sameSign = ((n1 < 0) == (n2 < 0));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jason Hall |
Solution 3 | Christoph |
Solution 4 | Christoph |
Solution 5 | sgowd |
Solution 6 | Pmpr.ir |