使用最多一次交换操作构造最大数字 C++
在这个问题中,我们得到一个正整数。我们的任务是创建一个程序,使用最多一次交换操作来构造最大数字。
我们将使用现有数字的数字创建一个新数字。
构成的最大数字只能交换现有数字的一个数字。
让我们举个例子来理解这个问题
Input: n = 63512 Output: 65312
解决方案方法
解决这个问题的一种方法是找到通过交换给定数字的数字对创建的所有数字。在所有这些交换数字的数字中,返回最大值。为此,我们将数字转换为字符串并交换位置。
示例
程序说明我们解决方案的工作原理
#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;
}输出
The number is 792156 The largest number created by swapping one digit is972156
另一种方法
解决这个问题的另一种方法是找到有助于构成最大可能数字的交换。为此,我们将从左到右扫描数字。然后交换第一对,其后一位数字大于前一位数字。此交换将产生最大数字。
示例
程序说明我们解决方案的工作原理
#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;
}输出
The number is 792156 The largest number created by swapping one digit is972156
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP