Skip to content

Instantly share code, notes, and snippets.

@wanderindev
Created July 1, 2022 21:07
Show Gist options
  • Save wanderindev/fc86202d900bd2a07f146a054091d24c to your computer and use it in GitHub Desktop.
Save wanderindev/fc86202d900bd2a07f146a054091d24c to your computer and use it in GitHub Desktop.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode()
curr_node = result
carry = 0
while l1 or l2 or carry:
digit_1 = l1.val if l1 else 0
digit_2 = l2.val if l2 else 0
addition = digit_1 + digit_2 + carry
carry = addition // 10
new_digit = addition % 10
curr_node.next = ListNode(new_digit)
curr_node = curr_node.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return result.next
# Test cases
l1 = ListNode(3)
l1.next = ListNode(4)
l1.next.next = ListNode(2)
l2 = ListNode(4)
l2.next = ListNode(6)
l2.next.next = ListNode(5)
solution = Solution()
sol = solution.add_two_numbers(l1, l2)
assert sol.val == 7
assert sol.next.val == 0
assert sol.next.next.val == 8
print(" ", l1.next.next.val, l1.next.val, l1.val)
print("+", l2.next.next.val, l2.next.val, l2.val)
print("---------")
print(" ", sol.next.next.val, sol.next.val, sol.val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment