Skip to content

Commit 3582b3f

Browse files
authored
Add files via upload
1 parent fa20ca7 commit 3582b3f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2. Add Two Numbers (Medium)
2+
3+
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
4+
5+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
6+
7+
8+
9+
Example 1:
10+
11+
12+
Input: l1 = [2,4,3], l2 = [5,6,4]
13+
Output: [7,0,8]
14+
Explanation: 342 + 465 = 807.
15+
Example 2:
16+
17+
Input: l1 = [0], l2 = [0]
18+
Output: [0]
19+
Example 3:
20+
21+
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
22+
Output: [8,9,9,9,0,0,0,1]
23+
24+
25+
Constraints:
26+
27+
The number of nodes in each linked list is in the range [1, 100].
28+
0 <= Node.val <= 9
29+
It is guaranteed that the list represents a number that does not have leading zeros.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
3+
dummy = ListNode(0)
4+
curr = dummy
5+
carry = 0
6+
7+
while carry or l1 or l2:
8+
if l1:
9+
carry += l1.val
10+
l1 = l1.next
11+
if l2:
12+
carry += l2.val
13+
l2 = l2.next
14+
curr.next = ListNode(carry % 10)
15+
carry //= 10
16+
curr = curr.next
17+
18+
return dummy.next

0 commit comments

Comments
 (0)