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
总结
如果您对本教程有任何问题,请在评论区提出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP