Given a number as string, output the next number in order. The digits you may use are only those already given, plus any number of 0's.
Example:
Given 1234, output 1243;
Given 4321, output 10234.
Solution:
The best approach is to make use of the C++ next_permutation template function from <algorithm> library. This template can work on a string and update it in place to the next string in lexicographical order. If the given string is already the largest one, then the function returns false and changes the string to the smallest one; otherwise, returns true and modifies the string to next one in order.
Code 1: first call next_permutation, then insert a zero if false returned.
Code 2: first insert a 0 to the beginning of the string, after permutation, remove it if it's still at the beginning.
It's better to look into the magic next_permutation template. When not allowed to use such library function, we may need write code similar to that.
Related Posts:
Next Number in Order without next_permutation
No comments:
Post a Comment