package miscellaneous;
public class Swap2NumberWithoutTempVariable {
public static void main(String[] args) {
int a =10;
int b=-1;
way1(a, b);
way2(a, b);
way3(a, b);
}
//Arithmetic Overflow Issue. If x and y are too large, addition and multiplication may go out of integer range.
private static void way1(int a, int b){
System.out.println("Before swap a="+a + " , " + "b="+b);
a=a-b;
b=a+b;
a=b-a;
System.out.println("After Swap a="+a + " , " + "b="+b);
}
private static void way2(int a, int b){
System.out.println("Before swap a="+a + " , " + "b="+b);
a=a^b;
b=a^b;
a=b^a;
System.out.println("After Swap a="+a + " , " + "b="+b);
//How this approach is working, lets see
//We want to change a to b and vice versa, if we change the bits of a to match exactly as b then a will become b.
//Now what are the bits difference between a and b that we will get using XOR and XOR will give 0 for same bits and 1 for non matching.
}
//The multiplication and division based approach will not work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.
private static void way3(int a, int b){
System.out.println("Before swap a="+a + " , " + "b="+b);
a=a*b;
b=a/b;
a=a/b;
System.out.println("After Swap a="+a + " , " + "b="+b);
}
}
Questions on Stack, Queues, Linkedlist, Binary Trees, Sorting, Searching, Graphs etc with solution using Java Language.
Tuesday, 19 May 2015
Swap 2 numbers without using any temporary variable
Labels:
miscellaneous
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment