From afed82b8eb71b37837d3c338800e770d72136750 Mon Sep 17 00:00:00 2001 From: Acuspeedster Date: Wed, 2 Oct 2024 17:05:46 +0530 Subject: [PATCH] feat: Implement XOR swap algorithm in JavaScript --- code/bit_manipulation/src/xor_swap/xor_swap.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 code/bit_manipulation/src/xor_swap/xor_swap.js diff --git a/code/bit_manipulation/src/xor_swap/xor_swap.js b/code/bit_manipulation/src/xor_swap/xor_swap.js new file mode 100644 index 0000000000..248225a015 --- /dev/null +++ b/code/bit_manipulation/src/xor_swap/xor_swap.js @@ -0,0 +1,16 @@ +// Part of Cosmos by OpenGenus Foundation + +function xorSwap(a, b) { + console.log(`Before swap: a = ${a}, b = ${b}`); + + a = a ^ b; // Step 1: a now contains the XOR of both + b = a ^ b; // Step 2: b gets the original value of a + a = a ^ b; // Step 3: a gets the original value of b + + console.log(`After swap: a = ${a}, b = ${b}`); +} + +// Example usage: +let x = 5; +let y = 10; +xorSwap(x, y);