Add Two Numbers
Detailed guide and Python implementation for the 'Add Two Numbers' problem.
1. 学ぶ
The 'Add Two Numbers' problem is a key challenge in the Linked List section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Add Two Numbers.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Add Two Numbers carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
問題提起
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
The linked lists are represented as Python lists. Implement a function addTwoNumbers(l1: list, l2: list) -> list that returns the sum as a list in reverse digit order.
- •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
例
[2,4,3], [5,6,4]
[7,0,8]
342 + 465 = 807. Represented in reverse: [7,0,8].
[0], [0]
[0]
0 + 0 = 0.
[9,9,9,9,9,9,9], [9,9,9,9]
[8,9,9,9,0,0,0,1]
9999999 + 9999 = 10009998. Represented in reverse: [8,9,9,9,0,0,0,1].
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
解決する準備はできましたか?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
インタビューの洞察とバリエーション
複雑さの分析の内訳
なぜ時間がかかるのか: Directly evaluates all possibilities.
なぜ宇宙なのか: Uses standard local memory.
なぜ時間がかかるのか: Optimized paths reduce total operations.
なぜ宇宙なのか: May trade memory for speed.
最適化されたソリューションの Python コード
最適化されたソリューションの Python コード
def add_two_numbers_opt(l1, l2):
if isinstance(l1, list):
node1 = build_linked_list(l1)
node2 = build_linked_list(l2)
res = add_two_numbers_opt_helper(node1, node2)
return linked_list_to_list(res)
return add_two_numbers_opt_helper(l1, l2)
def add_two_numbers_opt_helper(l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
curr.next = ListNode(total % 10)
curr = curr.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return dummy.nextブルート フォース コード (スポイラーガード付き)
ブルート フォース コード (スポイラーガード付き)
def add_two_numbers_brute(l1, l2):
if isinstance(l1, list):
node1 = build_linked_list(l1)
node2 = build_linked_list(l2)
res = add_two_numbers_brute_helper(node1, node2)
return linked_list_to_list(res)
return add_two_numbers_brute_helper(l1, l2)
def add_two_numbers_brute_helper(l1: ListNode, l2: ListNode) -> ListNode:
def to_num(node):
num, place = 0, 1
while node:
num += node.val * place
place *= 10
node = node.next
return num
total = to_num(l1) + to_num(l2)
dummy = ListNode(0)
curr = dummy
for digit in str(total)[::-1]:
curr.next = ListNode(int(digit))
curr = curr.next
return dummy.next or ListNode(0)Algorithm Pattern Checklist
When dealing with Linked List data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Standard Linked List problem properties apply.
関連する質問
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
推奨される Python リソース
関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。
Python ループ
Python ループを使用してデータを反復処理する方法を学びます。インタラクティブな例を使用して、for ループ、while ループ、ブレーク、継続、ループのベスト プラクティスをマスターします。
Python 辞書にキーを追加および更新する方法
Python 辞書で要素を追加したり、キーと値のペアを更新したりする方法を学びます。角括弧、更新メソッド、結合演算子のオプションを調べます。
Python 文字列メソッドのチートシート
Python 文字列操作の完全なリファレンス ガイド。文字列プロパティの書式設定、検索、分割、置換、チェックをマスターします。
Python と JavaScript: どちらのプログラミング言語が最適ですか?
Python と JavaScript の包括的な比較。構文の違い、パフォーマンス、使用例 (バックエンドとフロントエンド)、およびコーディング例を調べます。