- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Form the largest number using at most one swap operation C++
In this problem, we are given a positive integer. Our task is to create a program to form the largest number using at most one swap operation.
We will be creating a new number using the digits of the existing number.
The largest number formed can have only one digit swapped from the existing number.
Let’s take an example to understand the problem
Input: n = 63512 Output: 65312
Solution Approach
One method to solve the problem is by finding all the numbers created by swapping pair of digits of the given number. Out of all these swapped digit numbers, the largest one is returned. For this, we will convert the number to string and swap positions.
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; int findLargestNumSwapDig(int N){ string strNum = to_string(N); string temp = strNum; for (int i = 0; i < strNum.size(); i++) { for (int j = i + 1; j < strNum.size(); j++) { swap(strNum[i], strNum[j]); if (stoi(strNum) > stoi(temp)) temp = strNum; swap(strNum[i], strNum[j]); } } return stoi(temp); } int main(){ int num = 792156; cout<<"The number is "<<num<<endl; cout<<"The largest number created by swapping one digit is "<<findLargestNumSwapDig(num) << endl; return 0; }
Output
The number is 792156 The largest number created by swapping one digit is972156
Another approach
One more approach to solve the problem is by finding the swap which contributes to the largest possible number. For this, we will scan the number from left to right. And then swap the first pairs form which the next digit is greater than the previous digit. This swap will result in the largest number.
Example
Program to illustrate the working of our solution
#include <iostream> using namespace std; int findLargestNumSwapDig(int N){ int currMaxDig = -1; int currMaxInd = -1; int lSwap = -1; int rSwap = -1; string strNum = to_string(N); for (int i = strNum.size() - 1; i >= 0; i--) { if (strNum[i] > currMaxDig) { currMaxDig = strNum[i]; currMaxInd = i; continue; } if (strNum[i] < currMaxDig) { lSwap = i; rSwap = currMaxInd; } } if (lSwap == -1) return N; swap(strNum[lSwap], strNum[rSwap]); return stoi(strNum); } int main(){ int num = 792156; cout<<"The number is "<<num<<endl; cout<<"The largest number created by swapping one digit is "<<findLargestNumSwapDig(num) << endl; return 0; }
Output
The number is 792156 The largest number created by swapping one digit is972156