Skip to content

Latest commit

 

History

History
32 lines (26 loc) · 867 Bytes

03-Next-bigger-number-with-the-same-digits.md

File metadata and controls

32 lines (26 loc) · 867 Bytes

Next bigger number with the same digits

Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:

12 ==> 21
513 ==> 531
2017 ==> 2071

nextBigger(num: 12)   // returns 21
nextBigger(num: 513)  // returns 531
nextBigger(num: 2017) // returns 2071

If the digits can't be rearranged to form a bigger number, return -1 (or nil in Swift):

9 ==> -1
111 ==> -1
531 ==> -1

nextBigger(num: 9)   // returns nil
nextBigger(num: 111) // returns nil
nextBigger(num: 531) // returns nil

Solution

def next_bigger(n):
    my_list = sorted(list(str(n)))
    max_num = int("".join(my_list[::-1]))
    while n <= max_num:
        n += 1
        if sorted(list(str(n))) == my_list:
            return n
    return -1