In this tutorial, we are going to write a program that finds the largest number with a single swap.
Let's see the steps to solve the problem.
- Initialise the number n.
- Convert the integer to string.
- Write a loop that iterates from the ending of the string.
- Find the max digit and index.
- If the current digits is less than the max digit, then update start index with current index and end index with max digit index.
- If the start index is -1, then return n.
- Else swap the digits in the start and end indexes.
- Return the integer by converting.
Example
Let's see the code.
#include <bits/stdc++.h>
using namespace std;
int getLargestNumber(int n) {
int maxDigit = -1;
int maxDigitIndex = -1;
int startIndex = -1;
int endIndex = -1;
string nInStr = to_string(n);
for (int i = nInStr.size() - 1; i >= 0; i--) {
if (nInStr[i] > maxDigit) {
maxDigit = nInStr[i];
maxDigitIndex = i;
continue;
}
if (nInStr[i] < maxDigit) {
startIndex = i;
endIndex = maxDigitIndex;
}
}
if (startIndex == -1) {
return n;
}
swap(nInStr[startIndex], nInStr[endIndex]);
return stoi(nInStr);
}
int main() {
int n = 678;
cout << getLargestNumber(n) << endl;
return 0;
}Output
If you run the above code, then you will get the following result.
876
Conclusion
If you have any queries in the tutorial, mention them in the comment section.