Skip to content

Commit bd7ed64

Browse files
committed
Problem: add-two-numbers
1 parent 9c872e1 commit bd7ed64

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

AddTwoNumber.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Definition for singly-linked list.
2+
#class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
def add_two_ListNode(l1, l2, prevCarry):
8+
val1 = l1.val if l1 else 0
9+
val2 = l2.val if l2 else 0
10+
11+
sum = val1 + val2 + prevCarry
12+
carry = sum // 10
13+
remainder = sum % 10
14+
15+
ln = ListNode(remainder)
16+
if carry or ((l1 and l1.next) or (l2 and l2.next)):
17+
next1 = l1.next if l1 else None
18+
next2 = l2.next if l2 else None
19+
ln.next = add_two_ListNode(next1, next2, carry)
20+
21+
return ln
22+
23+
24+
class Solution:
25+
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
26+
return add_two_ListNode(l1, l2, 0)

0 commit comments

Comments
 (0)