A boy asked his mother for M rupees in integer and using digits of M he created another integer N which is greater than M and the difference between M and N must be the least possible. Now help the his mother to find the integer N.

For example:

M= 2345

output will be 2354 (=N)

since the difference between M and N will be 9 which is least.

similarly if M =321

output will be 321(=N)

since in this case the difference between M and N will be 0 which is again the least possible difference

can you share the question link

2 Likes

Sorry, but i donâ€™t have the link for the question.

thanks for the reply.

ohk, but i am not understanding how 321 can be greater than 321?

It is like , if thereâ€™s no choice then (321 - 321) will result in least possible difference so the program should print 321 as output.

i think q has some more illustrationâ€¦

1 Like

otherwise :-

print same when letters are descending

or reverse sort

the number and swap last two digits

1 Like

Okay , thanks for the help.

I think solution would be something like this :

Start from the 2nd last digit call it x.

Check if the digit after x i.e last digit is greater than x, if so just interchange the digits you will get the answer.

If not then make x = 3rd last digit.

Check if any digits after x are greater than x.

If both of them are greater ,select smallest from them and interchange it with x, you will get the answer.

If only one is greater interchange it with x you will get the answer.

If none is greater,make x = 4th last and continue the process.

If no such greater digit is found till x is 1st digit,then the number must be in descending order, so there will be no number greater than given number.So the answer will be number itself.

1 Like