C++


  • 0
    B

    I know many people use next_permutation. Here is the detail way.

    int nextGreaterElement(int n) {
        string str=to_string(n);
        int i=str.length()-1;
        while(i>0)
        {
            if(str[i]>str[i-1])
            {
                reverse(str,i,str.length()-1);
                int k=i;
                while(str[i-1]>=str[k])k++;
                swap(str[i-1],str[k]);
                long result=stol(str);
                return result<=INT_MAX?result:-1;
            }
            i--;    
        }
        return -1;
    }
    void reverse(string &s,int i,int j)
    {
        while(i<j)swap(s[i++],s[j--]);
        return;
    }

Log in to reply
 

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