Add Two Numbers
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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
Approach 1:
Recursive Solution
We go on adding both of the node values and the carry in a recursive manner , once we find any of the linked list is exhausted then the value assumed as 0 . Also we link each of the node to its previous node at the end of the recursion
class Solution(object):
def addTwoNumbers(self, l1, l2,carry=0):
#print(l1.val,l2.val,bool(l1),bool(l2))
val1,val2=0,0
val1=l1.val if l1 else 0
val2=l2.val if l2 else 0
carry,quotient=divmod(val1+val2+carry,10)
node=ListNode(quotient)
l1= l1.next if l1 else l1
l2= l2.next if l2 else l2
if l1 or l2 or carry:
node.next=self.addTwoNumbers(l1,l2,carry)
return node
Time: O(max(m,n)) m,n -> size of first and second linked list
Space: O(max(m,n))
Approach 2:
Same can be solved using the Iterative solution.
class Solution(object):
def addTwoNumbers(self, l1, l2):
carry=0
temp=ListNode(0)
node_=temp
while l1 or l2:
if l1 ==None:
one=0
else:
one=l1.val
if l2==None:
two=0
else:
two=l2.val
inter=ListNode((one+two+carry)%10)
temp.next=inter
temp=inter
carry=(one+two+carry)//10
if l1:
l1=l1.next
if l2:
l2=l2.next
if carry!=0:
temp.next=ListNode(carry)
return node_.next
Time: O(max(m,n)) m,n -> size of first and second linked list
Space: O(max(m,n))