Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two integers have the same sign

Tags:

javascript

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.

like image 824
Christoph Avatar asked Apr 24 '12 12:04

Christoph


People also ask

Is 0 an integer yes or no?

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, …..

How do you check if an integer is between two numbers?

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.


2 Answers

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

bool sameSign = (n1 * n2) > 0
like image 196
Jason Hall Avatar answered Sep 20 '22 16:09

Jason Hall


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 <

like image 25
user1346466 Avatar answered Sep 19 '22 16:09

user1346466