32 lines
914 B
Python
32 lines
914 B
Python
def next_bigger(n):
|
|
# get number as digits in list
|
|
digits = [int(x) for x in list(str(n))]
|
|
|
|
# find index of pivot. return -1 if there is no pivot, meaning number is alreadig biggest
|
|
pivot = -1
|
|
for i in range(1, len(digits)):
|
|
if digits[-i] > digits[-i - 1]:
|
|
pivot = -i - 1
|
|
break
|
|
|
|
if pivot == -1:
|
|
return -1
|
|
|
|
# find the smallest digit to the right that is bigger than the pivot
|
|
right = digits[pivot + 1 :]
|
|
swap = right.index(min([x for x in right if x > digits[pivot]]))
|
|
|
|
# swap pivot with found digit
|
|
digits[pivot], digits[len(digits) - len(right) + swap] = (
|
|
right[swap],
|
|
digits[pivot],
|
|
)
|
|
|
|
# sort right side of new swapped pivot and replace it at the end
|
|
right = digits[pivot + 1 :]
|
|
right.sort()
|
|
digits[pivot + 1 :] = right
|
|
|
|
# return number
|
|
return int("".join([str(x) for x in digits]))
|