Top 150 InterviewЛегко

Add Two Numbers

Detailed guide and Python implementation for the 'Add Two Numbers' problem.

Постановка задачи

Легко

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

Примеры

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?
Consider using Linked List-specific data structures like sets or heaps.
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.

Открыть в редакторе
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

Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.

Учебник по Python

Циклы Python

Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.

Посмотреть ресурс
Практическое руководство

Как добавить и обновить ключи в словаре Python

Узнайте, как добавлять элементы или обновлять пары «ключ-значение» в словаре Python. Изучите квадратные скобки, метод обновления и параметры оператора слияния.

Посмотреть ресурс
Шпаргалка

Шпаргалка по строковым методам Python

Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.

Посмотреть ресурс
Сравнение языков

Python против JavaScript: какой язык программирования лучше?

Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.

Посмотреть ресурс