From a5b9c46d4ca3b5b08975e508da3951316a36295a Mon Sep 17 00:00:00 2001 From: imshreya2000 <73038200+imshreya2000@users.noreply.github.com> Date: Thu, 26 Oct 2023 13:52:16 +0530 Subject: [PATCH] Create SwapWithoutTemp --- Bit-Manipulation/SwapWithoutTemp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Bit-Manipulation/SwapWithoutTemp diff --git a/Bit-Manipulation/SwapWithoutTemp b/Bit-Manipulation/SwapWithoutTemp new file mode 100644 index 0000000000..a035ac63d2 --- /dev/null +++ b/Bit-Manipulation/SwapWithoutTemp @@ -0,0 +1,14 @@ +function swapWithoutTemp(a, b) { + a = a ^ b; // Step 1: XOR a and b, store result in a + b = a ^ b; // Step 2: XOR new a (a ^ b) and original b, store result in b (now b = a) + a = a ^ b; // Step 3: XOR new a (a ^ b) and new b (a), store result in a (now a = b) +} + +let a = 5; +let b = 7; + +console.log(`Before Swap: a = ${a}, b = ${b}`); + +swapWithoutTemp(a, b); + +console.log(`After Swap: a = ${a}, b = ${b}`);