ในปัญหานี้ เราได้รับจำนวนเต็มบวก งานของเราคือสร้างโปรแกรมเพื่อสร้างจำนวนที่มากที่สุดโดยใช้การดำเนินการสลับอย่างน้อยหนึ่งครั้ง
เราจะสร้างหมายเลขใหม่โดยใช้ตัวเลขของหมายเลขที่มีอยู่
จำนวนสูงสุดที่เกิดขึ้นสามารถสลับจากตัวเลขที่มีอยู่ได้เพียงหลักเดียว
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
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