Thursday 17 November 2016

How to reverse two int variable without using temp variable in java ?

This question is frequently asked from most of the investment banking company such as Goldmann sachs, Morgan stanley and JP MC to check your basic mathematical skill.

Algorithm:

Step 1: Declare two variable a and b
Step 2: Add a+b and assign the result to a;
Step 3 : Subtract b from a and assign the result to b;
Step 4: Subtract a from b and assign the result to a;


Code:

public class Swapping {
public static void main(String[] args) {
   int a=-16;
   int b=19;
   System.out.println(" a : "+a+" b : "+b);
   a=a+b;
   b=a-b;
   a=a-b;
   System.out.println("After swapping a : "+a+" b : "+b);
}
}






If you like the above solution . Please share this blog

No comments:

Post a Comment

s