LeetCode 筆記 - 2. Add Two Numbers

題目在此 2. Add Two Numbers

給你兩個 Linked list,裏面各自 反序 存放一個數字
取出來相加之後,再依照 反序 的規則放進 Linked list

解題思維

在演算法上沒什麼特別,就是照著規則實作即可

Time complexity: O(n)

程式碼

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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:


def get_int(self, l):
temp = ''

while True:
temp = f'{l.val}{temp}'

if l.next is None:
break

l = l.next

return int(temp)

def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:

value = self.get_int(l1) + self.get_int(l2)
result = [int(x) for x in reversed(str(value))]

root = None
last_node = None
for x in result:
node = ListNode(x)

if root is None:
root = node
if last_node is not None:
last_node.next = node
last_node = node

return root

相關文章