Swap two numbers without using extra variable

Objective:  Write an algorithm to swap two numbers without using extra variable.

This is fun puzzle which is asked in the interview.

Approach:

Example:

a = 3, b = 5
a = a + b = 8
b = a – b = 8 – 5 = 3
a = a – b = 8 – 3 = 5
Now a = 5, b = 3

Code:

public class SwapNumbers {
public static void swap(int a, int b){
System.out.println("first number: " + a + " second number: " + b);
a = a + b;
b = a b;
a = a b;
System.out.println("After Swappng: first number: " + a + " second number: " + b);
}
public static void main(String[] args) {
int a = 3;
int b = 5;
swap(a,b);
}
}

view raw
SwapNumbers.java
hosted with ❤ by GitHub

Output:

first number: 3 second number: 5
After Swapping: first number: 5 second number: 3

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.