Trusted answers to developer questions

Ravi

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.

**Input:**

num1 = 10

num2 = 5

**Output:** false

**Input:**

num1 = -10

num2 = 5

**Output:** true

Numbers are stored in the form of `0`

s and `1`

s (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.

Assume the two numbers are `num1`

and `num2`

. The steps of the algorithm are as follows:

- Compute the XOR operation on
`num1`

and`num2`

. - If XOR of
`num1`

and`num2`

is a negative number, then the numbers are of opposite sign as the resulting sign bit is`1`

. - 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`

.

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)); } }

- 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`

.

RELATED TAGS

bit operations

algorithms

communitycreator

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses