Monday, October 2, 2023

 How to swap two numbers without using the third variable?



This is one of the oldest trick questions from a coding interview.

There are two arguably best ways we can swap two numbers without using the third variable:
  1. With addition and subtraction
  2. Using XOR operator

Below is the program that uses both ways:

public static void main(String[] args) {

int a = 5;
int b = 10;

a = a + b;
b = a - b;
a = a - b;

System.out.println("a: " + a);
System.out.println("b: " + b);

System.out.println("Using XOR...");

a = 5;
b = 10;

a = a ^ b;
b = a ^ b;
a = a ^ b;

System.out.println("a: " + a);
System.out.println("b: " + b);

} Output: a: 10 b: 5 Using XOR... a: 10 b: 5

The first approach works well in Java, but it can cause an overflow if the addition is more than the maximum value of int primitive as defined by Integer.MAX_VALUE and if subtraction is less than the minimum value, I mean Integer.MIN_VALUE in some other programming languages.

That is not an issue in Java since integer overflows are clearly defined, like Integer.MAX_VALUE + 1 will result in Integer.MIN_VALUE, which means if you do both addition and subtraction with the same set of numbers, your result will be fine.


That is all about how to swap two numbers without using the third variable.


No comments:

Post a Comment