This post is completed by 2 users

  • 1
Add to List
Medium

307. Swap two numbers using Bitwise XOR Operator

Objective- Given two numbers, swap both the numbers using XOR operators.

Example:

X = 4, Y = 8
Output: X = 8, Y= 4

Approach: XOR operator

There are many ways to swap two numbers but here we will discuss a solution to swap numbers using XOR(^) operator.

  1. Say numbers are x and y.
  2. Do x = x XOR y, this will set only the bits which are set either in x or in y. store it in x.
  3. Do y = x XOR y, this will set the bits which were set in original x so this will store the original value of x into y.
  4. Do x = x XOR y, this will set the bits which were set in original y so this will store the original value of y into x.
  5. See the Example below
Swap numbers using XOR

Code:

Output:

x: 4, y: 8
After swapping
x: 8, y: 4