w3resource

JavaScript - Swap two variables using bit manipulation

JavaScript Bit Manipulation: Exercise-2 with Solution

Swap Variables with Bits

Write a JavaScript program to swap two variables using bit manipulation.

Test Data:
(12, 15) -> (15,12)

Sample Solution:

JavaScript Code:

// Define a function to swap the values of two variables using bitwise XOR operations
const swap = (x, y) => {
  x = x ^ y // Perform bitwise XOR to swap values
  y = x ^ y // Perform bitwise XOR to swap values
  x = x ^ y // Perform bitwise XOR to swap values
  return {a:x, b:y} // Return an object with the swapped values
} 
x = 12 // Assign a value to variable x
y = 15 // Assign a value to variable y
console.log("Before swap: x = " + x + " and y = " + y) // Print the values of x and y before swapping
const {a,b} = swap(x, y) // Call the swap function and destructure the returned object
console.log("After swap: x = " + a + " and y = " + b) // Print the values of x and y after swapping

Output:

Before swap: x = 12 and y = 15
After swap: x = 15 and y = 12

Flowchart:

Flowchart: JavaScript - Swap two variables using bit manipulation.

Live Demo:

See the Pen javascript-bit-manipulation-exercise-1 by w3resource (@w3resource) on CodePen.


* To run the code mouse over on Result panel and click on 'RERUN' button.*

For more Practice: Solve these Related Problems:

  • Write a JavaScript function that swaps two integer variables using bitwise XOR without a temporary variable.
  • Write a JavaScript function that validates inputs and returns an error if non-numbers are provided before performing the swap.
  • Write a JavaScript function that demonstrates the swap process step-by-step using intermediate XOR values.
  • Write a JavaScript function that swaps two variables in an array using bit manipulation and returns the updated array.

Go to:


PREV : Opposite Signs.
NEXT : Count Zero Bits.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.