2. 两数相加
为保证权益,题目请参考 2. 两数相加(From LeetCode).
解决方案1
Python
python
# 2. 两数相加
# https://leetcode.cn/problems/add-two-numbers/
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(-1)
ans = head
add = 0
while l1 is not None and l2 is not None:
t = l1.val + l2.val + add
add = t // 10
t = t % 10
ans.next = ListNode(t)
ans = ans.next
l1 = l1.next
l2 = l2.next
while l1 is not None:
t = l1.val + add
add = t // 10
t = t % 10
ans.next = ListNode(t)
ans = ans.next
l1 = l1.next
while l2 is not None:
t = l2.val + add
add = t // 10
t = t % 10
ans.next = ListNode(t)
ans = ans.next
l2 = l2.next
if add != 0:
ans.next = ListNode(add)
head = head.next
return head
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52