Detect if two integers have opposite signs | GeeksforGeeks
Given two signed integers, write a function that returns true if the signs of given integers are different, otherwise false. The function should not use any of the arithmetic operators.
The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit as 1 iff they have opposite sign. In other words, XOR of x and y will be negative number number iff x and y have opposite signs
Given two signed integers, write a function that returns true if the signs of given integers are different, otherwise false. The function should not use any of the arithmetic operators.
The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit as 1 iff they have opposite sign. In other words, XOR of x and y will be negative number number iff x and y have opposite signs
bool
oppositeSigns(
int
x,
int
y)
{
return
((x ^ y) < 0);
}
bool
oppositeSigns(
int
x,
int
y)
{
return
((x ^ y) >> 31);
}
bool oppositeSigns( int x, int y) { return (x < 0)? (y >= 0): (y < 0); } |
The first method is more efficient. The first method uses a bitwise XOR and a comparison operator. The second method uses two comparison operators and a bitwise XOR operation is more efficient compared to a comparison operation.
Read full article from Detect if two integers have opposite signs | GeeksforGeeks