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.

  • Say numbers are x and y.
  • Do x = x XOR y, this will set only the bits which are set either in x or in y. store it in x.
  • 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.
  • 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.
  • See the Example below

Swap numbers using XOR

Java Code:


Output:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • lipsa patel

    In objective, “XOP” should be “XOR”

    • tutorialhorizon

      Thanks Lipsa. We have corrected the objective.

%d bloggers like this: