[英]next biggest number with same digits
我的代碼似乎是正確的,但如果不能生成更大的數字,我需要它返回 -1:
def next_bigger(n):
strNum = str(n)
length = len(strNum)
for i in range(length-2, -1, -1):
current = strNum[i]
right = strNum[i+1]
if current < right:
temp = sorted(strNum[i:])
next = temp[temp.index(current) + 1]
temp.remove(next)
temp = ''.join(temp)
return int(strNum[:i] + next + temp)
else:
return -1
return n
我試圖解決這個問題是行不通的:添加else
是我認為current
大於right
時的替代方法。
請幫忙!
無論如何,您的代碼流程是錯誤的:在您的循環中,您具有以下結構:
for A : if B : return else : return
所以你的程序總是會在第二次迭代之前終止。
在某些情況下,修復代碼比重寫代碼要困難得多。 我不確定這對您有多大幫助,但請嘗試以下代碼。
def next_bigger(n):
str_num = str(n)
size = len(str_num)
for i in range(2, size + 1):
sublist = list(str_num[-i:size])
temp = sorted(sublist, reverse=True)
if sublist != temp:
return int(str_num[:size-i] + ''.join(temp))
return -1
它的作用是從后面對數字進行切片(從 2 個元素切片開始,一直到len
)並檢查生成的切片是否在 join 時產生最大的數字。 如果不是,它將被下一個更大的替換並返回。 如果這對你有用,請告訴我。
例子
n = 4181536841
sublist = ['4', '1']
temp = ['4', '1'] # they are the same so no larger number can be produced just by looking at a slice of length 2.
#---------iteration 2---------------
sublist = ['8', '4', '1']
temp = ['8', '4', '1'] # they are again the same so no larger number can be produced just by looking at a slice of length 3.
#---------iteration 3---------------
sublist = ['6', '8', '4', '1']
temp = ['8', '6', '4', '1'] # now they are different. So produce a number out of temp (8641) ans stich it to the rest of the number (418153)
return 4181538641
EV。 庫尼斯錯了。 例如,在 4181536841 之后的下一個最大的是 4181538146,而不是 4181538641。
邏輯是這樣工作的:
1 - Find where list[-n] > list[-n - 1]
2 - find next number higher than list[-n] after list[-n]
3 - Switch next highest and list[-n - 1]
4 - reorder the remaining numbers after list[-n] from low to high
e.g. 29357632:
1 - list[-n] = 7 --> 2935[7]632
since 7 > 5
2 - next highest number after list[-n] (7) is the 6 --> 29357[6]32
3 - switch list[-n-1] and next highest number (switch 5 and 6) -->
293[6]7[5]32
4 - reorder rest of digits after list[-n-1] (6) --> 2936[7532] > 29362357
所以 29357632 之后的下一個最高數字是 29362357
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.