Leetcode Add Two Numbers problem solution in Python programming

In the Leetcode Add Two Numbers problem solution in Python programming 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.

Leetcode Add Two Numbers problem solution in Python programming

 def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode(0)
        cur = result
        n = 0
        while True:
            
            if l1 and l2:
                cur.next = ListNode(0)
                cur = cur.next
                cur.val = (l1.val+l2.val+n)%10
                n = int(l1.val+l2.val+n)/10
                l1 = l1.next
                l2 = l2.next
            elif l1 and not l2:
                cur.next = ListNode(0)
                cur = cur.next
                cur.val = (l1.val+n)%10
                n = int(l1.val+n)/10
                l1 = l1.next
            elif not l1 and l2:
                cur.next = ListNode(0)
                cur = cur.next
                cur.val = (l2.val+n)%10
                n = int(l2.val+n)/10
                l2 = l2.next
            else:
                break
        if n!=0:
            
            cur.next = ListNode(0)
            cur = cur.next
            cur.val = n
            
        return result.next



class Solution(object):
    def addTwoNumbers(self, a, b):
        digit_sum = a.val + b.val
        total_fr = total_bk = ListNode(digit_sum % 10)
        digit_sum //= 10
        a = a.next
        b = b.next
        while a or b or digit_sum:
            digit_sum += (a.val if a else 0) + (b.val if b else 0)
            total_bk.next = ListNode(digit_sum % 10)
            digit_sum //= 10
            total_bk = total_bk.next
            a = a.next if a else a
            b = b.next if b else b
        return total_fr

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *