Simple C++ using std::string and std::stoi()


  • 0
    class Solution {
    public:
        int maximumSwap(int num) {
            string str = to_string(num);
            if (str.size()==1) { return num; }
            for (int i=0; i < str.size()-1; i++){
                for (int j=i+1; j < str.size(); j++) {
                    string swapped = str;
                    swapped[i] = str[j];
                    swapped[j] = str[i];
                    int new_num = stoi(swapped);
                    if (new_num > num){
                        num = new_num;
                    }
                }
            }
            return num;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.