In this tutorial, we are going to write a program that finds the largest possible even number with a single swap of digits.
Let's see the steps to solve the problem.
- Initialise the number in string format.
- Iterate over the given number.
- Find the even digit that is less than or equal to the last digit of the number.
- Break the loop if you find the desired even digit.
- If the even digit doesn't exist, then return the given number.
- Swap the last digit with the even digit you found in the above step.
- Return the number
Example
#include <bits/stdc++.h>
using namespace std;
string getLargestEvenNumber(string number, int n) {
int even = INT_MAX, index;
for (int i = 0; i < n - 1; i++) {
if ((number[i] - '0') % 2 == 0) {
even = (number[i] - '0');
index = i;
}
if (even <= (number[n - 1] - '0')) {
break;
}
}
if (even == INT_MAX) {
return number;
}
swap(number[index], number[n - 1]);
return number;
}
int main() {
string number = "15433";
cout << getLargestEvenNumber(number, 5) << endl;
return 0;
}Output
If you run the above code, then you will get the following result.
15334
Conclusion
If you have any queries in the tutorial, mention them in the comment section.