给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
方案一:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
i, s1, l = 1, 0, l1
while l:
s1 += l.val * i
i = i * 10
l = l.next
i, s2, l = 1, 0, l2
while l:
s2 += l.val * i
i *= 10
l = l.next
s = s1 + s2
s = str(s)[:: -1]
res = [ListNode(int(ch)) for ch in s]
for i in range(len(res) - 1):
res[i].next = res[i + 1]
return res[0]