Objective– Given two numbers, swap both the numbers using XOR operators.
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
x: 4, y: 8 After swapping x: 8, y: 4