-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumber2_add_two_numbers.py
More file actions
37 lines (28 loc) · 1.05 KB
/
number2_add_two_numbers.py
File metadata and controls
37 lines (28 loc) · 1.05 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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
firstNum = l1
secondNum = l2
carry = 0
resultNode = ListNode()
resultNodeStart = resultNode
while(firstNum is not None or secondNum is not None):
if(firstNum is None):
firstNum = ListNode()
if(secondNum is None):
secondNum = ListNode()
add = firstNum.val + secondNum.val + carry
carry = add//10
add = add%10
resultNode.next = ListNode(val=add)
resultNode = resultNode.next
firstNum = firstNum.next
secondNum = secondNum.next
if(carry != 0):
resultNode.next = ListNode(val=carry)
resultNodeStart = resultNodeStart.next
return resultNodeStart