Solution #1: Using Arithmetic Operator
public class SwapVariablesDemo1
{
public static void main(String[] args)
{
int x = 1;
int y = 2;
System.out.println("Values before swapping: x = " + x + ", y = " + y);
x = x + y; // x = 3, y = 2
y = x - y; // x = 3, y = 1
x = x - y; // x = 2, y = 1
System.out.println("Values after swapping: x = " + x + ", y = " + y);
}
}
Output:
Values before swapping: x = 1, y = 2
Values after swapping: x = 2, y = 1
Solution #2: Using XOR Bitwise Operator
Aside from the arithmetic solution, the more technical way to solve this problem is to use the XOR bitwise operator. The XOR bitwise operator returns 0 if both operands are the same and returns 1 if both operands are different (refer to the XOR truth table below).
| X | Y | X ^ Y |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
public class SwapVariablesDemo2
{
public static void main(String[] args)
{
int x = 1; // 0001 in binary
int y = 2; // 0010 in binary
System.out.println("Values before swapping: x = " + x + ", y = " + y);
x = x ^ y; // x = 3 (0011), y = 2 (0010)
y = x ^ y; // x = 3 (0011), y = 1 (0001)
x = x ^ y; // x = 2 (0010), y = 1 (0001)
System.out.println("Values after swapping: x = " + x + ", y = " + y);
}
}
Output:
Values before swapping: x = 1, y = 2
Values after swapping: x = 2, y = 1
If you want to impress your future employer during your programming exam, then I suggest that you use the XOR bitwise solution provided that you can explain the logic behind it.
Now, try asking your fellow developers this question and find out how many of them know the solution :)
No comments:
Post a Comment