[
math
linked list
]
BinarySearch 0242 Add Linked Lists
Problem statement
https://binarysearch.com/problems/Add-Linked-Lists/
Solution
Equal to Leetcode 0002. Add Two Numbers.
Complexity
Time complexity is O(m + n)
for time and O(max(m, n))
for space.
Code
class Solution:
def solve(self, l1, l2):
carry = 0
head = curr = LLNode(0)
while l1 or l2 or carry:
d1, d2 = 0, 0
if l1:
d1 = l1.val
l1 = l1.next
if l2:
d2 = l2.val
l2 = l2.next
carry, digit = divmod(d1 + d2 + carry, 10)
curr.next = LLNode(digit)
curr = curr.next
return head.next