C++ 中允許單次交換的最大數字
在本教程中,我們準備編寫一個可以查詢具有單次交換的最大數字的程式。
讓我們看看解決該問題所需要的步驟。
- 初始化數字 n。
- 將整數轉換為字串。
- 編寫一個迴圈,從字串結尾處開始迭代。
- 查詢最大的數字和索引。
- 如果當前數字小於最大數字,則使用當前索引更新開始索引,並使用最大數字索引更新結束索引。
- 如果開始索引為 -1,則返回 n。
- 否則,交換開始索引和結束索引處的數字。
- 透過轉換返回整數。
示例
我們來看一看程式碼。
#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
總結
如果您對本教程有任何問題,請在評論區提出。
廣告