1123456784987654321
2start with a number
3
4123456784 987654321
5 ^the first place from the right where the left-digit is less than the right
6 Digit "x" is 4
7
8123456784 987654321
9 ^find the smallest digit larger than 4 to the right
10
11123456785 4 98764321
12 ^place it to the left of 4
13
14123456785 4 12346789
15123456785123446789
16 ^sort the digits to the right of 5. Since all of them except
17 the '4' were already in descending order, all we need to do is
18 reverse their order, and find the correct place for the '4'
19
1def findnext(ii):
2 iis=list(map(int,str(ii)))
3 for i in reversed(range(len(iis))):
4 if i == 0: return ii
5 if iis[i] > iis[i-1] :
6 break
7 left,right=iis[:i],iis[i:]
8 for k in reversed(range(len(right))):
9 if right[k]>left[-1]:
10 right[k],left[-1]=left[-1],right[k]
11 break
12 return int("".join(map(str,(left+sorted(right)))))
13