Wednesday, 4 May 2016

Check whether two numbers are of opposite signs or not using Java .....

Problem -Two numbers are given ,you have to evaluate whether they are of opposite signs or not

Logic -Numbers are represented in 2's complemented form in computer where sign bit 0 means it is 
            positive number and 1 means it is negative .

here is the code ......


       
public class CheckOppositeSigns {

 public static void main(String args[]) {
  int x = 2;
  int y = -13;
  if (checkForOppositeSigns(x, y))
   System.out.print("Yes both the integers are of opposite signs");
  else
   System.out.print("Both the integers are of same sign");
 }

 public static boolean checkForOppositeSigns(int x, int y) {

  int signofFirstVariable = (x >> 31) ^ (0x1); //shifting the variable to place the sign bit at unit                                                                                     //position and then XOR with 000000000
  int signofSecondVariable = (y >> 31) ^ (0x1);
  if (signofFirstVariable != signofSecondVariable)
   return true;

  return false;
 }
}

       
 

No comments:

Post a Comment