-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path65.py
More file actions
37 lines (28 loc) · 959 Bytes
/
65.py
File metadata and controls
37 lines (28 loc) · 959 Bytes
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def fromListToNumber(l: Optional[ListNode]) -> int:
str_num = ""
next_ptr = l
while next_ptr is not None:
str_num = f"{next_ptr.val}" + str_num
next_ptr = next_ptr.next
return int(str_num)
def fromNumberToList(num: int) -> ListNode:
res = []
for digit in str(num):
res.append(int(digit))
list_node = ListNode(res[0], None)
if len(res) > 1:
for digit in res[1:]:
old_node = list_node
list_node = ListNode(digit, old_node)
return list_node
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
num_a = fromListToNumber(l1)
num_b = fromListToNumber(l2)
product_sum = num_a + num_b
return fromNumberToList(product_sum)