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.
Yes, 0 is an integer. By the definition, integers are the numbers that include whole numbers and negative natural numbers. We know that natural numbers are counting numbers that start with 1, 2, …..
To check if a number is between two numbers: Use the && (and) operator to chain two conditions. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range.
You can multiply them together; if they have the same sign, the result will be positive.
bool sameSign = (n1 * n2) > 0
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 <
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With