Check if two numbers have opposite signs using bitwise operator

Problem Statement

Given two numbers, print true if the numbers have opposite signs and print false if the numbers are of the same sign. Solve the problem using the bitwise operator.

Example 1:

Input:
num1 = 10
num2 = 5

Output: false

Example 2:

Input:
num1 = -10
num2 = 5

Output: true

Intuition and algorithm

Numbers are stored in the form of 0s and 1s (i.e. binary representation) in computer memory. The sign bit is 1 for negative numbers and 0 for positive numbers.

Hence, XOR operation on numbers with opposite signs results in 1 as the sign bit, and XOR operation on numbers with the same signs results in 0 as the sign bit.

Solution

Assume the two numbers are num1 and num2. The steps of the algorithm are as follows:

  1. Compute the XOR operation on num1 and num2.
  2. If XOR of num1 and num2 is a negative number, then the numbers are of opposite sign as the resulting sign bit is 1.
  3. If XOR of num1 and num2 is a positive number, then the numbers are of the same sign as the resulting sign bit is 0.

Code

public class Main {
static boolean hasOppositeSigns(int num1, int num2) {
return (num1 ^ num2) < 0;
}
public static void main(String[] args)
{
int num1 = 50, num2 = -75;
System.out.printf("%s and %s are of opposite sign? %s\n", num1, num2, hasOppositeSigns(num1, num2));
num2 = 32;
System.out.printf("%s and %s are of opposite sign? %s\n", num1, num2, hasOppositeSigns(num1, num2));
num1 = -1;
num2 = -9;
System.out.printf("%s and %s are of opposite sign? %s\n", num1, num2, hasOppositeSigns(num1, num2));
}
}

Explanation

  • Lines 3–5: We define a method called hasOppositeSigns that takes two integers as parameters. It checks whether the XOR operation of the two integers is less than zero or not.
  • Line 9: Define the two integers num1 and num2.
  • Line 10: Call the hasOppositeSigns method to check if the numbers have the same or opposite signs.
  • Lines 12–17: Call the hasOppositeSigns method for different values of num1 and num2.

Free Resources