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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /** * 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