

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Largest number with one swap allowed in C++
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.
- Related Questions & Answers
- Largest smaller number possible using only one swap operation in C++
- Form the largest number using at most one swap operation C++
- Largest even number possible by using one swap operation in given number in C++
- Next higher number using atmost one swap operation in C++
- Previous Permutation With One Swap in Python
- Game of Nim with removal of one stone allowed in C++
- Largest number with prime digits in C++
- Form the smallest number using at most one swap operation in C++
- Swap two variables in one line in C/C+
- Swap two variables in one line using C#
- Count number of triplets with product equal to given number with duplicates allowed in C++
- Finding the maximum number using at most one swap in JavaScript
- Minimize Cost with Replacement with other allowed in C++
- Program to find Lexicographically Smallest String With One Swap in Python
- Check if array can be sorted with one swap in Python
Advertisements