stoi的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35747066/article/details/89435498

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_35747066/article/details/89435498