Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions leetCode/LinkedList/add-two-numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
carry = 0
resp = ListNode(0)
it = resp
while l1 and l2:
it.next = ListNode(0)
it = it.next
it.val = carry + l1.val + l2.val
carry = it.val // 10
it.val %= 10
l1 = l1.next
l2 = l2.next

while l1:
it.next = ListNode(0)
it = it.next
it.val = carry + l1.val
carry = it.val // 10
it.val %= 10
l1 = l1.next

while l2:
it.next = ListNode(0)
it = it.next
it.val = carry + l2.val
carry = it.val // 10
it.val %= 10
l2 = l2.next

if carry > 0:
it.next = ListNode(carry)

return resp.next