Very basic interview question : Swap two variables without using third or temporary variables. This serves the purpose of getting started with the interview. There are 3 ways to do this and we will discus all of them now
- Addition
- XOR operation(bitwise operator)
- Multiplication
By Addition
/** * Created with IntelliJ IDEA. * User: aniket * Date: 19/12/13 * Time: 8:20 PM */ public class VariableSwapper { public static void main(String args[]){ int a = 4; int b = 5; System.out.println("***** Swapping using Addition *****"); System.out.println("Before Swapping a : " + a); System.out.println("Before Swapping b : " + b); a = a + b; b = a - b; a = a - b; System.out.println("After Swapping a : " + a); System.out.println("After Swapping b : " + b); } }
By XOR operation
/** * Created with IntelliJ IDEA. * User: aniket * Date: 19/12/13 * Time: 8:20 PM */ public class VariableSwapper { public static void main(String args[]){ int a = 4; int b = 5; System.out.println("***** Swapping using XOR *****"); System.out.println("Before Swapping a : " + a); System.out.println("Before Swapping b : " + b); a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("After Swapping a : " + a); System.out.println("After Swapping b : " + b); } }
By Multiplication
/** * Created with IntelliJ IDEA. * User: aniket * Date: 19/12/13 * Time: 8:20 PM */ public class VariableSwapper { public static void main(String args[]){ int a = 4; int b = 5; System.out.println("***** Swapping using Multiplication *****"); System.out.println("Before Swapping a : " + a); System.out.println("Before Swapping b : " + b); a = a * b; b = a / b; a = a / b; System.out.println("After Swapping a : " + a); System.out.println("After Swapping b : " + b); } }
Output remains the same except printing the method part.
***** Swapping using Multiplication *****
Before Swapping a : 4
Before Swapping b : 5
After Swapping a : 5
After Swapping b : 4
XOR logic can be better understood with following diagram