2_Add Two Numbers
2. Add Two Numbers
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.Solution 1: detailed version
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret = ListNode(-1)
cur = ret
carry = 0
while l1 or l2:
if l1:
value1 = l1.val
l1 = l1.next
else:
value1 = 0
if l2:
value2 = l2.val
l2 = l2.next
else:
value2 = 0
if value1 + value2 + carry >= 10:
cur_sum = value1 + value2 + carry - 10
carry = 1
else:
cur_sum = value1 + value2 + carry
carry = 0
cur.next = ListNode(cur_sum)
cur = cur.next
if carry == 1:
cur.next = ListNode(1)
return ret.nextSolution 2: compressed version
Last updated