Here are some interesting ways to swap numbers in C++
Kajanthan sureshkumar
C++ Developer | R&D @SPIL Labs | Simulation Software Developer | Qt, MFC, OpenGL, Open CASCADE, Socket Programming
1. Using a Temporary Variable: This method involves using a third variable to temporarily hold the value of one of the variables while swapping their values.
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b = 10;
int temp;
temp = a;
a = b;
b = temp;
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
2. Using Addition and Subtraction: Basic arithmetic operations can be used to swap values by adding and subtracting.
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b = 10;
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
3. Using Multiplication and Division: Similar to addition and subtraction method, but uses multiplication and division.
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b = 10;
a = a * b;
b = a / b;
a = a / b;
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
4. Using Bitwise XOR: A common method in programming interviews, XOR operation efficiently swaps values without the need for a temporary variable.
领英推荐
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
5.Using 'std::swap' from '<algorithm>':
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a = 5;
int b = 10;
swap(a, b);
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}