File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ # add two numbers | leetcode 02 | https://leetcode.com/problems/add-two-numbers/
2
+
3
+ # Definition for singly-linked list.
4
+ class ListNode :
5
+ def __init__ (self , val = 0 , next = None ):
6
+ self .val = val
7
+ self .next = next
8
+
9
+ class Solution :
10
+ def addTwoNumbers (self , l1 : list [ListNode ], l2 : list [ListNode ]) -> list [ListNode ]:
11
+ res = ListNode ()
12
+ head = res
13
+
14
+ while l1 != None or l2 != None :
15
+ if l1 == None :
16
+ this_val = res .val + l2 .val
17
+ l2 = l2 .next
18
+ elif l2 == None :
19
+ this_val = res .val + l1 .val
20
+ l1 = l1 .next
21
+ else :
22
+ this_val = res .val + l1 .val + l2 .val
23
+ l1 , l2 = l1 .next , l2 .next
24
+
25
+ this_digit = this_val % 10
26
+ next_digit = this_val // 10
27
+
28
+ res .val = this_digit
29
+ if l1 != None or l2 != None :
30
+ res .next = ListNode (next_digit )
31
+ res = res .next
32
+
33
+ if next_digit > 0 :
34
+ res .next = ListNode (next_digit )
35
+ res = res .next
36
+
37
+ return head
38
+
You can’t perform that action at this time.
0 commit comments