Method 1:
Input:
But question:
Swap two numbers with using a third variable???
let a = 5;
let b = 10;
console.log("Before swapping:");
console.log("a =", a);
console.log("b =", b);
// Switching the values
let temp = a;
a = b;
b = temp;
console.log("After swapping:");
console.log("a =", a);
console.log("b =", b);
Output:
Method 2:
swap variable values without using a third variable:
let a = 5;
let b = 10;
console.log("Before swapping:");
console.log("a =", a);
console.log("b =", b);
// Switching the values without a third variable
a = a + b;
b = a - b;
a = a - b;
console.log("After swapping:");
console.log("a =", a);
console.log("b =", b);
Output:
Method 3:
Input:
// Swapping variable values using destructuring assignment
let x = 5;
let y = 10;
console.log("Before swapping:");
console.log("x =", x);
console.log("y =", y);
console.log("After swapping:");
[x, y] = [y, x];
console.log("x =", x);
console.log("y =", y);
Output:
Method 4:
Bitwise XOR approach:
Things will be more clear if you notice the truth table of Bitwise XOR(^):
| Input X | Input Y | Output (X ^ Y) |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
a = 50 (base 10) -> 0110010 (base 2)
50 ÷ 2 = 25 reminder 0 (Least Significant Bit - LSB) |
25 ÷ 2 = 12 reminder 1
12 ÷ 2 = 6 reminder 0
6 ÷ 2 = 3 reminder 0
3 ÷ 2 = 1 reminder 1
1 ÷ 2 = 0 reminder 1 (Most Significant Bit - MSB) |
- Assemble the remainders backwards:
To construct the binary number, read the recorded
remainders from the bottom (the last division step)
up to the top (the first division step)
- The last remainder(1) is the most significant bit (MSB)
- The first remainder (0) is the least significant bit (LSB).
Reading upward gives:
110010
- Add standard bit padding:
In computing, binary sequences are often padded
with leading zeros to meet specific
bit-width requirements (such as 7-bit or 8-bit registers).
Because adding a zero to the
left side of a whole number does not change
its numerical value,
110010 becomes:
0110010
a = 50 (base 10) -> 0110010 (base 2)
b = 100 (base 10) -> 1100100 (base 2)
a = a ^ b
0110010
1100100
-------------
(XOR)1010110
b = a ^ b
1010110
1100100
-------------
(XOR)0110010 [Equivalent to 50(base 10)]
a = a ^ b
1010110
0110010
-------------
(XOR)1100100 [Equivalent to 100(base 10)]
Finally a = 100 and b = 50
Input:
let a = 5;
let b = 10;
console.log("Before swapping:");
console.log("a =", a);
console.log("b =", b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log("After swapping:");
console.log("a =", a);
console.log("b =", b);
Output:




Top comments (0)