- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.py
More file actions
Latest commit
37 lines (30 loc) · 1.01 KB
/
Copy path2.py
File metadata and controls
37 lines (30 loc) · 1.01 KB
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
# Name: Add Two Numbers
# Link: https://leetcode.com/problems/add-two-numbers/
# Method: Build new linked list, keep going as long as one head present (or a carry)
# Time: O(n)
# Space: O(n)
# Difficulty: Medium
classListNode:
def__init__(self, val=0, next=None):
self.val=val
self.next=next
classSolution:
defaddTwoNumbers(self, l1: ListNode, l2: ListNode) ->ListNode:
# Consider case when not same len
res_head=ListNode()
res_now=res_head
l1_head=l1
l2_head=l2
carry=0
whilel1_headorl2_headorcarry:
sum_now= (
(l1_head.valifl1_headelse0)
+ (l2_head.valifl2_headelse0)
+carry
)
res_now.next=ListNode(sum_now%10)
carry=sum_now//10
res_now=res_now.next
l1_head=l1_head.nextifl1_headelseNone
l2_head=l2_head.nextifl2_headelseNone
returnres_head.next