标签:ati ber wrapper elf numbers 开头 style pre nbsp
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
1 # Definition for singly-linked list.
2 class ListNode:
3 def __init__(self, x):
4 self.val = x
5 self.next = None
6
7
8 class Solution:
9 def addTwoNumbers(self, l1, l2):
10 """
11 :type l1: ListNode
12 :type l2: ListNode
13 :rtype: ListNode
14 """
15 head = ListNode(0)
16 cur = head
17 m = 0
18 while True:
19 if l1 is not None:
20 a = l1.val
21 else:
22 a = 0
23 if l2 is not None:
24 b = l2.val
25 else:
26 b = 0
27 if l1 is None and l2 is None and m == 0:
28 return head.next
29 else:
30 add = a + b + m
31 cur.next = ListNode(add % 10)
32 m = (a+b+m) // 10
33 cur = cur.next
34 if l1 is not None:
35 l1 = l1.next
36 if l2 is not None:
37 l2 = l2.next
标签:ati ber wrapper elf numbers 开头 style pre nbsp
原文地址:https://www.cnblogs.com/Lin-Yi/p/9601194.html