Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Given a number, how do we find the next greater number with the same digits?
num = raw_input()
ind = len(num)-1
while ind > 0 and num[ind] <= num[ind-1]:
ind -= 1
#There is no greater number with the same digits
if ind == 0:
print "Not possible"
else:
result = num[0:ind-1] #the left part
l_digit = num[ind-1] #left digit to be swapped
g_digit = num[ind] #candidate for digit to be swapped
right_digits = [num[ind]]
g_ind = ind+1
while g_ind < len(num):
right_digits.append(num[g_ind])
if num[g_ind] > l_digit and num[g_ind] < g_digit:
g_digit = num[g_ind]
g_ind += 1
result += g_digit
right_digits.remove(g_digit)
right_digits.append(l_digit)
right_digits.sort()
result += "".join(right_digits)
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment