使用最多一次交換操作構造最大數字 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