Leetcode problem 2 Solution using Python - Add Two Numbers

Leetcode problem 2 Solution using Python - Add Two Numbers

Here is solution of leetcode problem 2 using Python


Problem

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.


Solution

Inputs are singly-linked lists not normal lists. Let's create the singly-linked list using Python first so you can understand the problem better. 

class ListNode:
  def __init__(self, val=0, next=None):
      self.val = val
      self.next = next
l1 = ListNode(0)
l1.next = ListNode(2)
l2 = ListNode(1)
n1 =  ListNode(4)
l2.next = n1
n2 = ListNode(5)
n1.next = n2

_ l1 and l2 are single-linked lists. l1 is similar to 0 -> 2 -> None  and l2 is similar to 1 -> 4 -> 5 -> None.

_ Here is the solution. You can copy & paste this code to the leetcode. 

class Solution:
  def addTwoNumbers(self, l1, l2):
    new = ListNode(0)
    temp = None 
    carry = 0 
    while (l1 or l2 or carry):
      if l1:
        carry = carry + l1.val
        l1 = l1.next
      if l2:
        carry = carry + l2.val
        l2 = l2.next
      rem = carry % 10
      e = ListNode(rem)
      if temp:
        temp.next = e
      else:
        new.next = e
      temp = e 
      carry = carry//10
    return new.next

Calling the function - No need to submit this code to the leetcode. This is only for our understanding. 

class ListNode:
  def __init__(self, val=0, next=None):
      self.val = val
      self.next = next
  def __str__(self):
    s1 = ""
    while self:
      s1 = s1  + str(self.val) + "->"
      self = self.next
    return s1
l1 = ListNode(0)
l1.next = ListNode(2)
print(l1)
l2 = ListNode(1)
n1 =  ListNode(4)
l2.next = n1
n2 = ListNode(5)
n1.next = n2
print(l2)
s = Solution()
l3 = s.addTwoNumbers(l1,l2)
print(l3)

Outcome 

0->2->
1->4->5->
1->6->5->


Thanks for reading the article. Keep learning