Skip to content
August 10, 2024

Swapping Two Numbers Without Using a Temporary Variable

· 2 min read · Algorithm & Design

I recently stumbled upon this question: How do you swap two numbers without using a temporary variable? This took me back to my college days when I memorized this program without fully understanding the logic.

Later on, I learned how it works, and today I met someone with the same question, so I thought of writing about it.

Understanding XoR

XOR, or Exclusive OR, is a logical operation that outputs true (1) if the inputs differ and false (0) if they are the same. The basic rule is:

  • If the bits are different, XoR returns 1.
  • If the bits are the same, XoR returns 0.

Consider two binary numbers, A and B:

  • A: 1010
  • B: 1100

When you apply XOR to each corresponding bit:

A = 1010
B = 1100
A XoR B = 0110

Breaking it down y applying XoR rule:

  • 1 XoR 1 = 0 (same)
  • 0 XoR 1 = 1 (different)
  • 1 XoR 0 = 1 (different)
  • 0 XoR 0 = 0 (same)

So, 1010 XoR 1100 results in 0110.

Now , the question Swapping Variables Without a Third Variable

Traditionally, swapping two variables involves using a temporary variable to hold one value while the other is overwritten. However, XOR offers an alternative solution.
Here’s how it works:

  1. Calculate the XOR of the two numbers and store it in one of them.
  2. XOR the result from step 1 with the other number. This effectively stores the first number’s value in the second variable.
  3. XOR the result from step 2 with the first number. This restores the second number’s original value in the first variable.

Example with a java program

public class XORSwap {
    public static void main(String[] args) {
        int x = 5; // binary: 0101
        int y = 3; // binary: 0011

        System.out.println("Before swap: x = " + x + ", y = " + y);

        x = x ^ y;   // x becomes 0101 ^ 0011 = 0110 
        y = x ^ y;   // y becomes 0110 ^ 0011 = 0101 (binary for 5)
        x = x ^ y;   // x becomes 0110 ^ 0101 = 0011 (binary for 3)

        // Now, x is 3 and y is 5
        System.out.println("After swap: x = " + x + ", y = " + y);
    }
}

This technique leverages the properties of XOR to swap values without using extra memory.

Using XOR to swap variables is often considered more of a programming puzzle than a practical solution. In most cases, using a temporary variable is simpler to understand and maintain.

Thanks !

Leave a Reply