150強訪談簡單

兩個數字相加

「兩個數字相加」問題的詳細指南和 Python 實作。

問題陳述

簡單

給您兩個表示兩個非負整數的非空鍊錶。這些數字以相反的順序存儲,並且每個節點都包含一個數字。將兩個數字相加並以鍊錶形式傳回總和。

您可以假設這兩個數字不包含任何前導零,除了數字 0 本身。

連結列表表示為 Python 列表。實作一個函數 addTwoNumbers(l1: list, l2: list) -> list ,以相反的數字順序將總和傳回為列表。

約束條件
  • The number of nodes in each linked list is in the range [1, 100]
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros

範例

Example 1
Input
[2,4,3], [5,6,4]
Output
[7,0,8]
Explanation

342 + 465 = 807. Represented in reverse: [7,0,8].

Example 2
Input
[0], [0]
Output
[0]
Explanation

0 + 0 = 0.

Example 3
Input
[9,9,9,9,9,9,9], [9,9,9,9]
Output
[8,9,9,9,0,0,0,1]
Explanation

9999999 + 9999 = 10009998. Represented in reverse: [8,9,9,9,0,0,0,1].

Need a Hint?
考慮使用特定於連結清單的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。