Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สร้างตัวเลขที่มากที่สุดโดยใช้การสลับได้สูงสุดหนึ่งครั้งใน 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