Skip to content

Instantly share code, notes, and snippets.

@KyleJamesWalker
Created April 18, 2014 19:34
Show Gist options
  • Save KyleJamesWalker/bccce780c69916b4b781 to your computer and use it in GitHub Desktop.
Save KyleJamesWalker/bccce780c69916b4b781 to your computer and use it in GitHub Desktop.
'''
Quick and dirty code to see if I could figure out the next
larger number with all the same digits of the number passed.
Note: After coming up with the solution I found the following
http://stackoverflow.com/questions/9368205/given-a-number-find-the-next-higher-number-which-has-the-exact-same-set-of-digi
'''
def get_next(the_num):
the_num = str(the_num)
last = -1
for x in xrange(-1, -len(the_num)-1, -1):
if last > the_num[x]:
# x is the index of the number that needs to be moved
left = the_num[:x]
mid = the_num[x]
right = sorted(the_num[x+1:])
found = -1
for x in xrange(len(right)):
if int(right[x]) > int(mid):
found = x
break
if found != -1:
the_num = list(left) + [right[found]]
right[found] = mid
the_num += sorted(right)
break
last = the_num[x]
return int(''.join(the_num))
val = 23468
last = -1
while(last != val):
print val
last = val
val = get_next(val)
print val
# S/O Numbers:
# print 123456784987654321
# print get_next(123456784987654321)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment