python3:LeetCode第二题 两数相加

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。python3:LeetCode第二题 两数相加

# 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
“”"
s1, s2 = 0, 0
i = 1
while l1 or l2:
if l1:
s1 += l1.val * i
l1 = l1.next
if l2:
s2 += l2.val * i
l2 = l2.next
i *= 10

    s = s1 + s2                            
    s = str(s)[::-1]                       
    l = [ListNode(int(i)) for i in s]      
                                           
    for i in range(len(l) - 1):            
        l[i].next = l[i + 1]               
                                           
    return l[0]                            

python3:LeetCode第二题 两数相加