Python 中的加一操作


假設我們有一個整數陣列 A。A 將儲存 n 個元素,且這些元素都是非負數。整個陣列 A 表示一個大數字。因此如果給定 A = [5, 3, 2, 4],則它表示數字 5324。我們必須使用該陣列 A,將數字加 1,然後返回數字(如給定陣列所示)。因此加 1 後,A 將變成 [5, 3, 2, 5]

要解決這個問題,我們將遵循以下步驟。

  • 獲取陣列,將每個字元追加到一個字串中以使其成為字串
  • 然後將字串轉換為整數,再將數字加 1
  • 然後拆分每個數字並生成另一個陣列

讓我們檢視以下實現以獲得更好的理解 −

示例(Python)

 即時演示

class Solution(object):
   def plusOne(self, digits):
      """
      :type digits: List[int]
      :rtype: List[int]
      """
      num = ""
      for i in digits:
         num +=str(i)
      num = int(num)
      num+=1
      num = str(num)
      ans = []
      for i in num:
         ans.append(int(i))
      return ans
digits = [5,3,2,4]
ob1 = Solution()
print(ob1.plusOne(digits))

輸入

digits = [5,3,2,4]

輸出

[5,3,2,5]

更新於: 2020 年 4 月 28 日

2000+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.