A mixture of bitwise operators and arithmetic operators
The idea is the same as discussed in Method 1 but uses Bitwise addition and subtraction for swapping.
Example: Below is the implementation of the above approach.
function swap(a, b) {
// same as a = a + b
a = (a & b) + (a | b);
// same as b = a - b
b = a + (~b) + 1;
// same as a = a - b
a = a + (~b) + 1;
console.log("After swapping: a = " +
a + ", b = " + b);
}
let a = 5, b = 10;
console.log("Before swapping: a = " +
a + ", b = " + b);
// Function Call
swap(a, b);
Output
Before swapping: a = 5, b = 10 After swapping: a = 10, b = 5
Time Complexity: O(1).
Auxiliary Space: O(1), since no extra space has been taken.
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