Detect If Two Integers Have Opposite Signs
In this lesson, we detect if two integers have different signs. Ignore the values of the inputs for this problem and focus on the signs.
We'll cover the following
Introduction
In this question, input two numbers and detect if they have opposite signs.
Problem statement
We need to write a program to detect if two input integers have opposite signs.
Input: a = 100, b = -1
Output: "Signs are opposite"
Input: a = 100, b = 501
Output: "Signs are not opposite."
Concept
We have already learned about representing/finding a positive/negative number in the NOT
lesson.
Two rules:
If the leading bit on the left side is 0, then it is a positive number.
If the leading bit on the left side is 1, then it is a negative number.
Solution
The XOR rule says the output will be 1
only when two input values are opposite (0 and 1, or 1 and 0).
The above concept clearly says if the leading left-MSB (left-most significant bit) is 1
, then it’s negative.
The following four examples will clearly explain these concepts.
-
Consider two numbers whose left MSBs are both
1
, and the XOR of them is0
. -
If two numbers both have left MSBs of
0
, then the XOR of them is0
. -
Now, when the left MSB of two inputs is different, then the XOR yields to
1
, which is a negative number.
So, when we perform (x ^ y) < 0
, we get the right answer.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.