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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。