Understanding the Problem
We are given two integers, x
and y
. Our goal is to swap their values — that is, after the swap, x
should hold the original value of y
and y
should hold the original value of x
.
However, we are not allowed to use a temporary variable to hold one of the values during the swap. This means we must find a way to perform the swap in-place, using only arithmetic or bitwise operations.
We will use the XOR (^
) bitwise operator to solve this problem. XOR has a unique property: applying XOR twice with the same value restores the original number.
Step-by-Step Solution with Example
Step 1: Start with two numbers
Let’s say we have x = 4
and y = 7
. Our goal is to swap them using XOR.
Binary representation:
Step 2: Perform x = x ^ y
Now x
becomes:
x = 4 ^ 7 = 0100 ^ 0111 = 0011 → x = 3
Now, x = 3
and y = 7
Step 3: Perform y = x ^ y
Now we use the new x
(which is 3) to update y
:
y = 3 ^ 7 = 0011 ^ 0111 = 0100 → y = 4
Now, x = 3
and y = 4
Step 4: Perform x = x ^ y
Use the new y
to update x
:
x = 3 ^ 4 = 0011 ^ 0100 = 0111 → x = 7
Now, x = 7
and y = 4
Step 5: Final Output
We have successfully swapped the values. The output is:
[7, 4]
Edge Cases
- Same numbers: If
x
and y
are the same (e.g., x = y = 5
), the XOR trick still works and the values remain unchanged.
- Zero involved: XOR works fine even if one or both values are 0. For example,
x = 0
, y = 9
swaps correctly to [9, 0]
.
- Negative numbers: The XOR operation works at the bit level, so it can also handle negative integers correctly.
- Large numbers: XOR is a bitwise operation, so it can handle large integers within the bounds of your programming language’s integer type without overflow.
Final Thoughts
Swapping two numbers using XOR is a neat trick that avoids using extra memory. It's commonly asked in technical interviews to test understanding of bitwise operations and in-place algorithms.
However, for general code readability and safety, especially in production, using a temporary variable is often preferred unless you're working under strict memory constraints.
Still, this is a powerful technique worth knowing and practicing!
Comments
Loading comments...