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. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.