Skip to main content

Swapping Values Without Intermediate Variables

· One min read

Here are three methods to swap values without using intermediate variables.

1. Addition and Subtraction

Assume we have variables:

let a = 2, b = 5

Swap:

a = a + b // a = 7

b = a - b // b = 2

a = a - b // a = 5

Disadvantages:

  • Can only handle numeric values
  • May overflow when adding large numbers

2. Multiplication and Division

Since we have addition and subtraction, we can naturally think of multiplication and division:

a = a * b // a = 10

b = a / b // b = 2

a = a / b // a = 5

Disadvantages:

  • Precision loss
  • Divisor cannot be 0

3. XOR Method

XOR is a mathematical operation where different values yield 1, same values yield 0:

Result
000
011
101
110

To perform XOR operations in computers, we need to convert values to binary first. a in binary is 010, b in binary is 101:

a = a ^ b // 010 ^ 101 = 111

b = a ^ b // 111 ^ 101 = 010

a = a ^ b // 111 ^ 010 = 101

Disadvantages:

  • Cannot handle floating-point variables

Summary

All three methods are clever tricks, only for learning purposes. It's best not to use them in production environments.