stoi的使用
原创
©著作权归作者所有:来自51CTO博客作者wx596330ff6d68f的原创作品,请联系作者获取转载授权,否则将追究法律责任
670. Maximum Swap
Medium
51942FavoriteShare
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.
class Solution {
public:
int maximumSwap(int num) {
string tmp = to_string(num);
int MAX = num;
for(int i = 0;i < tmp.length();i ++){
for(int j = i + 1;j < tmp.length();j ++){
swap(tmp[i],tmp[j]);
int TmpNum = stoi(tmp);
if(TmpNum > MAX){
MAX = TmpNum;
}
swap(tmp[i],tmp[j]);
}
}
return MAX;
}
};