Swap Two Numbers

In this lesson, we make use of the XOR operator to swap the values of two inputs.

Introduction

In this question, input two numbers and swap them without using the swapping logic.

Problem statement

We need to write a program to swap two numbers.

Input: a = 10, b = 121
 
Output: a = 121, b = 10

Solution

We can make use of XOR to swap two values. You will find the solution below:

class SwapTwoNumbers {
public static void main(String[] args) {
int a = 10, b = 121;
a = a ^ b;
b = b ^ a;
a = a ^ b;
System.out.println("Finally, after swapping; a = " + a + " , b = " + b);
}
}

Complexity analysis

Time Complexity: We are not running a loop or scaling the inputs. The inputs never change. So the operation takes a single unit of time, which is O(1)O(1).

Space Complexity: We didn’t create an extra memory for this. So, the space complexity is O(1)O(1).

Access this course and 1400+ top-rated courses and projects.