Skip to content

Commit f15db87

Browse files
committed
O(n) time and O(1) space
1 parent d89f7e5 commit f15db87

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
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 contain a single digit. Add the two numbers and return it as a linked list.
3+
4+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
5+
6+
Example:
7+
8+
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
9+
Output: 7 -> 0 -> 8
10+
Explanation: 342 + 465 = 807.
11+
"""
12+
# Definition for singly-linked list.
13+
# class ListNode:
14+
# def __init__(self, val=0, next=None):
15+
# self.val = val
16+
# self.next = next
17+
class Solution:
18+
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
19+
head1,head2 = l1,l2
20+
temp = ListNode(-100)
21+
cur = temp
22+
carry,total = 0,0
23+
while head1 or head2:
24+
a = head1.val if head1 else 0
25+
b = head2.val if head2 else 0
26+
cur_total = a + b + carry
27+
carry = cur_total // 10
28+
temp.next = ListNode(cur_total % 10)
29+
temp = temp.next
30+
if head1:
31+
head1 = head1.next
32+
if head2:
33+
head2 = head2.next
34+
if carry:
35+
temp.next = ListNode(carry)
36+
return cur.next

0 commit comments

Comments
 (0)