在 Python 中插入 5 使數字最大


假設我們有一個數字 n,我們要找出在數字中任何位置插入 5 後可以形成的最大數字。

因此,如果輸入為 n = 826,則輸出將為 8526。

為解決此問題,我們將按照以下步驟進行操作 −

  • temp := n 作為字串
  • ans := -inf
  • 對於從 0 到 temp 大小的 i,進行操作
    • cand := 從索引 0 到 i 的 temp 子字串連線“5”連線從索引 i 到結尾的 temp 子字串
    • 如果 i 與 0 相同且 temp[0] 與“-”相同,則
      • 轉到下一個迭代
    • ans := ans 和數字 cand 的最大值
  • 返回 ans

讓我們來看一下以下實現以更好地理解 −

示例

 實際演示

class Solution:
   def solve(self, n):
      temp = str(n)
      ans = float('-inf')
      for i in range(len(temp) + 1):
         cand = temp[:i] + '5' + temp[i:]
         if i == 0 and temp[0] == '-':
            continue
            ans = max(ans, int(cand))
      return ans
ob = Solution()
print(ob.solve(826))

輸入

826

輸出

8526

更新於:2020 年 9 月 23 日

439 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告