
Swap Two Numbers Without a Temp Variable
Swap Two Numbers Without a Temp Variable
The Challenge: Math Magic!
How do you swap the values of two numbers, A and B, without using a third, temporary variable C?
Think it’s impossible? Think again! This is a classic problem that tests your understanding of basic
arithmetic.
Let’s say A = 5 and B = 10. Your mission, should you choose to accept it, is to swap these values so
that A becomes 10 and B becomes 5, all without using a temporary variable.
Hint: Crack the Code!
Ready for a hint? Think about how addition and subtraction can be used to manipulate the values in a
way that allows you to achieve the swap. Don’t let the simplicity fool you; it’s all about the
order of operations!
Can you solve this mathematical puzzle? Put on your thinking cap!
The Solution: Unveiled!
Here’s one way to do it using addition and subtraction:
let a = 5;
let b = 10;
console.log("Before swap: a = " + a + ", b = " + b);
a = a + b; // a is now 15 (5 + 10)
b = a - b; // b is now 5 (15 - 10)
a = a - b; // a is now 10 (15 - 5)
console.log("After swap: a = " + a + ", b = " + b);
Explanation:
- First, we add A and B and store the result in A.
- Then, we subtract B from the new value of A and store the result in B. This gives B the original
value of A. - Finally, we subtract B (which now holds the original value of A) from A (which holds the sum of the
original A and B) to get the original value of B, and store it in A.
Brain Check!
Now that you’ve seen one solution, can you think of other ways to swap two numbers without using a
temporary variable? (Hint: Explore bitwise XOR operation!)
Share your solutions and thoughts in the comments below! Let’s get those brain cells firing!




