Posted on 2023-07-17 15:55
Uriel 阅读(34)
评论(0) 编辑 收藏 引用 所属分类:
数据结构 、
闲来无事重切Leet Code
链表形式存储的大数加法,参考了Discussion的简洁写法
1 #445
2 #Runtime: 56 ms (Beats 64.47%)
3 #Memory: 13.6 MB (Beats 13.21%)
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def addTwoNumbers(self, l1, l2):
12 """
13 :type l1: ListNode
14 :type l2: ListNode
15 :rtype: ListNode
16 """
17 n1, n2 = [], []
18 while l1:
19 n1.append(l1.val)
20 l1 = l1.next
21 while l2:
22 n2.append(l2.val)
23 l2 = l2.next
24 t = 0
25 ans = None
26 while n1 or n2 or t:
27 v1 = n1.pop() if n1 else 0
28 v2 = n2.pop() if n2 else 0
29 t, v = divmod(v1 + v2 + t, 10)
30 node = ListNode(v)
31 node.next = ans
32 ans = node
33 return ans or ListNode(0)