Computer >> Computer tutorials >  >> Programming >> C++

Largest smaller number possible using only one swap operation in C++


In this tutorial, we are going to write a program that finds the largest number with a single swap that is less than the given number n.

Let's see the steps to solve the problem.

  • Initialise the number n.
  • Iterate from the end of the string and find the index of the digit which is greater than its next digit. Store it in a variable.
  • Break the loop as soon as u find it.
  • Iterate over the number from the end of the string to the above index.
    • Find the index of the digit which is less the above indexed digit and is greater among all in the area.
  • Swap the digits at the above two indexes. Return the updated number.

Example

Let's see the code.

#include <bits/stdc++.h>
using namespace std;
string getTheNumber(string str) {
   int length = str.length();
   int index = -1;
   for (int i = length - 2; i >= 0; i--) {
      if (str[i] > str[i+1]) {
         index = i;
         break;
      }
   }
   int smallerDigitIndex = -1;
   for (int i = length - 1; i > index; i--) {
      if (str[i] < str[index]) {
         if (smallerDigitIndex == -1 || str[i] >= str[smallerDigitIndex]) {
            smallerDigitIndex = i;
         }
      }
   }
   if (index == -1) {
      return "-1";
   }
   if (smallerDigitIndex != -1) {
      swap(str[index], str[smallerDigitIndex]);
      return str;
   }
   return "-1";
}
int main() {
   string str = "54624";
   cout << getTheNumber(str) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

54426

Conclusion

If you have any queries in the tutorial, mention them in the comment section.