C++ program to find the next greatest number from the same set of digits
As clear from the name we have to find a number which is smallest in all the number greater than the given number with same set of digits.
For example:
If n = 123456
Then the next number greater than this is 123465
If n = 7531
Then no number is possible which is greater than this with same set of digits.
Same set of digits means that we can only use 7,5,3,1 to form a new number as given in the above example.
Algorithm:
There are three cases that we have to keep in mind:
1) If all the digits are in decreasing order then no number greater than the given number is possible.
2) If all the digits are in increasing order then we just need to swap the last two digits to find the next greatest number.
3) This is the most important and of course the general case, this can be solved by doing following steps:
A) Traverse the given number from the last digit until you find a digit smaller than its preceding digit. If you did not find it then number greater than the given number is not possible, if you find that digit ("say x") then from x traverse to the right until you find a digit smallest in all the digits present on the right side of "x" but greater than "x".
For example:
If number is 125643
Then x will be 5 as 5 is smaller than 6
And the next digit will be 6 as 6 is the only digit on the right which is greater than 5
B) Now swap the two digits you found in previous step
So now the number will become 126543
C) Now sort all the digits from the position next to "x" up to the end in increasing order.
So the desired output is 126345
Consider the program:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer