---
# System prepended metadata

title: 'level 4:Next bigger number with the same digits(2019-12-02)'
tags: [python, Codewars]

---

# level 4:Next bigger number with the same digits(2019-12-02)
###### tags: `Codewars` `python`
You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:
<pre>
12 ==> 21
513 ==> 531
2017 ==> 2071
</pre>
If no bigger number can be composed using those digits, return -1:
<pre>
9 ==> -1
111 ==> -1
531 ==> -1
</pre>
my code:
<pre>
def next_bigger(n):
    import itertools 
    numlist =  [int(i) for i in str(n)]
    newlist = set(list(itertools.permutations(numlist,len(numlist))))
    new=[]
    for i in newlist:
        number=''
        for j in i:
            number = number+str(j)
        new.append(int(number))
    if n == max(new):
        return -1
    else:        
        return sorted(new)[sorted(new).index(n)+1]
</pre>
計算時間過長~~

修改為:
<pre>
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))
</pre>
