Swap Two Variables Using XOR
Last Updated :
26 Feb, 2024
In C++, variables are containers that store data. Sometimes, we may need to swap the values of two variables. The traditional method involves using a third variable as a temporary storage to facilitate the swap. In this article, we will learn how to swap two variables using the XOR technique.
Example:
Input: a = 5; b = 10;
Output: a = 10; b = 5;
Swapping Two Variables Using XOR in C++
The XOR operator returns true if the number of true inputs is odd. To swap two variables using XOR in C++, wc can do it byBy performing the XOR operation on the two variables three times, we can swap their values without using a third variable. Here’s how it works:
C++ Program to Swap Two Variables Using XOR
C++ Program to Swap Two Variables Using XOR
C++
#include <iostream>
using namespace std;
int main()
{
int a = 2, b = 3;
cout << "Before swapping the variables a= " << a
<< " b= " << b;
cout << endl;
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping the variables a= " << a
<< " b= " << b << endl;
return 0;
}
|
Output
Before swapping the variables a= 2 b= 3
After swapping the variables a= 3 b= 2
Time Complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...