# C++ 4 lines (next_permutation)

• ``````int nextGreaterElement(int n) {
auto digits = to_string(n);
next_permutation(begin(digits), end(digits));
auto res = stoll(digits);
return (res > INT_MAX || res <= n) ? -1 : res;
}
``````

• 表示受到一万点暴击。。。。。。。。。。

• +1....................

• If you know `next_permutation`, this problem somehow becomes a easy question.

• I think that the question is asking you to interpret the next permutation in your own way. One should check leetcode question 31. I don't believe that any interviewer will be satisfied by this answer.

• @justin40 I think that the point of this problem is to recognize and apply the next premutation. Problem 31, in contrary, specifically asks to implementation next premutation.

As an interviewer, I would add points if a candidate is familiar with next_permutation. I may ask to implement it, but probably I would just move on to more interesting problems.

• This post is deleted!

• There are this kind of operations !

• @pance +10086

• What kind of solution is this?!

• With next_permutation implemented myself

``````class Solution {
public:
int nextGreaterElement(int n) {
string nums = to_string(n);
if(!nextPermutation(nums)) return -1;
long long result=stoll(nums);
return (result>INT_MAX || result<=n)? -1:result;
}
private:
bool nextPermutation(string& nums) {
if(nums.empty()) return false;
int i=nums.size()-1;
while(i>=1 && nums[i]<=nums[i-1]) i--;
if(i==0) return false; // no next permutation, i.e. already largest

int j=nums.size()-1;
while(nums[j]<=nums[i-1]) j--;
swap(nums[i-1],nums[j]);

reverse(nums.begin()+i,nums.end());
return true;
}
};
``````

• si gao yi...

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