leetcode-2-两数相加

题目

https://leetcode.cn/problems/add-two-numbers/

题解

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
# 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
l3 = ListNode()
p = l3

need_add = 0
num = l1.val+l2.val
p.val = num%10 + need_add
need_add = num//10

l1 = l1.next
l2 = l2.next

while l1 != None and l2 != None:
num = l1.val+l2.val + need_add
p.next = ListNode(num%10)
p = p.next
need_add = num//10

l1 = l1.next
l2 = l2.next

while l1 != None:
num = l1.val + need_add
p.next = ListNode(num%10)
p = p.next
need_add = num//10

l1 = l1.next

while l2 != None:
num = l2.val + need_add
p.next = ListNode(num%10)
p = p.next
need_add = num//10

l2 = l2.next

if need_add>0:
p.next = ListNode(need_add)

return l3