Thursday, September 22, 2011

Next bigger number

Q : You have given a positive number. You have to find a number which is immediate bigger than that by using same digits available in the number. use same digits with same number of time, coming in positive integer and if a small number is not possible then we have to return -1.

For example: (1) You have given a number 7585 , your output should be 7855 . (2) 7111, return –1

Algorithm:


Code:

1 comment:

Eric Pruneau said...

put the number in a char array arr[]
scan the array from last to begining.
if arr[i] > arr[i-1] swap them and break
If you scan the array without swapping element, return -1.

put the array back to an integer.

So for 4385, you would swap 8 and 3

O(n+n+n) where n is the number of digits