Add Two Numbers
LeetCode 2
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = node =ListNode('#')
carry = 0
# step 1: tried to l1 l2 move
# step 4: what if l1 and l2 are None but carry is out there?
# add "carry" to the condition of while.
while l1 or l2 or carry:
v1, v2 = 0, 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
# step 2: carry variable is needed
carry, cursum = divmod(carry+v1+v2, 10)
# step 3: a dummy node is needed.
node.next = ListNode(cursum)
node = node.next
return dummy.next
Last updated