Java program to check whether 2 numbers have opposite signs

Hi Everyone, this blog post is about how to check whether 2 numbers have the opposite signs. The immediate solution which comes to our mind when we see this question is check using ' if ' loop. But there is much simpler way than doing this. When we see the integers in terms of bits, we can see that if the integer is negative, the MSB (Most Significant Bit) of that integer is set to 1. The MSB is 0 if the integer is positive.

So, the algorithm to check whether 2 numbers have opposite signs is based on bits. We just needed to XOR both the numbers. An XOR would return 1, if there is 1 and 0 or 0 and 1. For similar numbers, they will just return 0. If we XOR both the numbers, the result should be negative if both the numbers have different sign and it will be positive if both the numbers have same sign.

The java program is as follows:

public class DifferentSigns {
    
    public static void main(String args[])
    {
        int num1=-20;
        int num2=37;
        if(isDifferent(num1,num2))
        {
            System.out.println("The sign of numbers are different");
        }
        else
        {
            System.out.println("The sign of numbers are same");
        }
    }
    
    public static boolean isDifferent(int x, int y)
    {
        return ((x^y)<0);
    }
}


The output for the program is as follows:

The sign of numbers are different


We can also solve this program by right shifting the number 31 times and returning true or false if it is 1 or 0 respectively. To know more about shift operators, please check my post Shift operators.  The alternative way is as follows:

public static boolean isDifferent1(int x, int y)
    {
        int res =x^y>>31;
        if(res==1)
            return true;
        else
            return false;
    }


I hope this blog helps in understanding how to check whether 2 numbers have opposite signs. Please comment below if you have any doubts. All comments will be responded soon.

Thank you for reading the post.

Similar posts

1) Program to check whether a number is a power of multiple of 2.


Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++