Skip to main content
5 of 6
added 656 characters in body
mrakosms
  • 113
  • 1
  • 6

Next bigger number with the same digits

I have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits: 59853 -> 83559

Please let me know if there are any better solutions. I would like feedback how to improve this.

def next_bigger(num):
    numlist = [int(i) for i in str(num)]

    index_of_replace_num = -1
    i = len(numlist) - 1
    while i > 0:
        if numlist[i] > numlist[i-1]:
            index_of_replace_num = i - 1
            break
        i -= 1

    if index_of_replace_num == -1:
        return -1
    else:
        firstlist = numlist[:index_of_replace_num]
        replaced_num = numlist[index_of_replace_num]
        secondlist = numlist[index_of_replace_num+1:]
        new_replaced_num = 9
        i = 0
        delindex = 0
        while i < len(secondlist):
            if secondlist[i] > replaced_num and secondlist[i] < new_replaced_num:
                new_replaced_num = secondlist[i]
                delindex = i
            i += 1

        secondlist.pop(delindex)
        secondlist.append(replaced_num)
        firstlist.append(new_replaced_num)
        output = firstlist + sorted(secondlist)
        return int(''.join(str(x) for x in output))

Thanks for @jamie the link.

def next_bigger(num):
    digits = [int(i) for i in str(num)]

    i = len(digits) - 1
    while i > 0 and digits[i - 1] >= digits[i]:
        i -= 1
    if i <= 0:
        return -1

    swap_idx = len(digits) - 1
    while digits[swap_idx] <= digits[i - 1]:
        swap_idx -= 1
    digits[i - 1], digits[swap_idx] = digits[swap_idx], digits[i - 1]

    digits[i : ] = digits[len(digits) - 1 : i - 1 : -1]
    return int(''.join(str(x) for x in digits))
mrakosms
  • 113
  • 1
  • 6