One Line Expression
We can write only one line to swap two numbers.
- x = x ^ y ^ (y = x);
- x = x + y – (y = x);
- x = (x * y) / (y = x);
- x , y = y, x (In Python)
Example: Below is the implementation of the above approach.
// Javascript program to swap two
// numbers without using temporary
// variable
let x = 10, y = 5;
console.log("Before Swapping: x = " + x + ", y = " + y);
// Code to swap 'x' and 'y'
x = (x * y)/(y = x);
console.log("After Swapping: x = " + x + ", y = " + y);
Output
Before Swapping: x = 10, y = 5 After Swapping: x = 5, y = 10
Time Complexity: O(1)
Auxiliary Space: O(1)
Javascript program to swap two numbers without using temporary variable
To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable.
Below are the approaches used to swap two numbers without using a temporary variable:
Table of Content
- Using Arithmetic Operators
- Using Bitwise XOR
- A mixture of bitwise operators and arithmetic operators
- One Line Expression