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:

public class SwapNumbers {
static void swap(int x, int y){
System.out.println("x: " + x + ", y: " + y);
//x : 4 => 0100
//y: 8 => 1000
x = x ^ y;
//x:1100, y: 1000
y = x ^ y;
//x:1100, y:0100
x = x ^ y;
//x:1000, y:0100
System.out.println("After swapping");
System.out.println("x: " + x + ", y: " + y);
}
public static void main(String[] args) {
int x = 4;
int y= 8;
swap(x,y);
}
}

view raw
SwapNumbers.java
hosted with ❤ by GitHub

Output:

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

2 thoughts on “Swap two numbers using Bitwise XOR Operator”

Leave a Reply to tutorialhorizon Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.