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

ตัวเลขมากที่สุดที่อนุญาตให้สลับได้ 1 ครั้งใน C++

โจทย์

ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมหาตัวเลขมากที่สุดด้วยการสลับครั้งเดียว

มาดูขั้นตอนการแก้ปัญหา

  • กำหนดตัวเลข n
  • แปลงจำนวนเต็มเป็นสตริง
  • เขียนลูปที่วนรอบจากท้ายของสตริง
    • หาหลักมากที่สุดและดัชนี
    • ถ้าหลักปัจจุบันน้อยกว่าหลักมากที่สุด ให้อัปเดต start index ด้วยดัชนีปัจจุบันและ end index ด้วยดัชนีหลักมากที่สุด
  • ถ้า start index เป็น -1 ให้คืนค่า n
  • มิฉะนั้น สลับหลักที่ start และ end indexes
  • คืนค่าจำนวนเต็มโดยแปลงกลับ

ตัวอย่าง

มาดูโค้ดกัน

#include <bits/stdc++.h> 
using namespace std; 

int getLargestNumber(int n) { 
    int maxDigit = -1; 
    int maxDigitIndex = -1; 
    int startIndex = -1; 
    int endIndex = -1; 
    string nInStr = to_string(n); 
    for (int i = nInStr.size() - 1; i >= 0; i--) { 
        if (nInStr[i] > maxDigit) { 
            maxDigit = nInStr[i]; 
            maxDigitIndex = i; 
            continue; 
        } 
        if (nInStr[i] < maxDigit) { 
            startIndex = i; 
            endIndex = maxDigitIndex; 
        } 
    } 
    if (startIndex == -1) { 
        return n; 
    } 
    swap(nInStr[startIndex], nInStr[endIndex]); 
    return stoi(nInStr); 
} 

int main() { 
    int n = 678; 
    cout << getLargestNumber(n) << endl; 
    return 0; 
}

ผลลัพธ์

หากคุณรันโค้ดข้างต้น คุณจะได้ผลลัพธ์ดังนี้

876

สรุป

หากคุณมีคำถามในบทช่วยสอนนี้ ให้กล่าวถึงในส่วนความคิดเห็น