问题描述:
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
示例:
Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7.
Input: 9973 Output: 9973 Explanation: No swap.
问题分析:
交换任意两个位上的数字,重构后的数值比较大小,最大的那个即为答案。
过程详见代码:
class Solution {
public:
int maximumSwap(int num) {
vector<int> v;
int res = num,t = num;
while (num)
{
v.emplace_back(num % 10);
num /= 10;
}
reverse(v.begin(), v.end());
int n = v.size();
for (int i = 0; i < n; i++)
{
num = t;
for (int j = i + 1; j < n; j++)
{
num += (v[j] - v[i]) * pow(10, n - i - 1);
num += (v[i] - v[j]) * pow(10, n - j - 1);
res = max(num, res);
num = t;
}
}
return res;
}
};