Search⌘ K
AI Features

Swap Two Numbers

Explore how to swap two numbers without traditional swapping logic by using the bitwise XOR operator. Understand and apply an efficient solution that operates in constant time and space, enhancing your algorithm skills focused on bit manipulation.

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).