题目描述:
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.
Example 1:
Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973 Output: 9973 Explanation: No swap.
Note:
- The given number is in the range [0, 10^8]
class Solution {
public:
int maximumSwap(int num) {
string s=to_string(num);
int i=-1, j=-1;
int max_index=s.size()-1;
// 从字符串末尾开始遍历
for(int k=s.size()-2;k>=0;k--)
{ // 如果能找到k使得k小于当前最大值,说明已经找到一对可以交换的数字
if(s[k]<s[max_index])
{
i=k;
j=max_index;
}
// 找到了更大的数字,但是不确定是否有可以交换的另一个数字,所以先更新下标
else if(s[k]>s[max_index]) max_index=k;
}
if(i!=-1) swap(s[i],s[j]);
return stoi(s);
}
};