# 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
"""
add = 0
cur_node = ListNode(0)
rt_node = cur_node
while (l1 is not None or l2 is not None):
a1 = l1.val if l1 is not None else 0
a2 = l2.val if l2 is not None else 0
s = a1 + a2 + add
add = 0
if s / 10 > 0:
add = s / 10
cur_node.next = ListNode(s % 10)
cur_node = cur_node.next
l1 = l1.next if l1 is not None else None
l2 = l2.next if l2 is not None else None
if add > 0:
cur_node.next = ListNode(add)
return rt_node.next
leetcode 两数相加
最新推荐文章于 2024-03-16 13:21:13 发布