LeetCode 2 - Add Two Numbers Problem

Problem Statement

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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution:

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy_head = ListNode(0) l3 = dummy_head carry=0 while l1!=None or l2!=None: l1_value = l2_value = 0 if l1!=None: l1_value = l1.val if l2!=None: l2_value = l2.val current_sum = l1_value + l2_value + carry carry = current_sum//10 last_digit = current_sum%10 new_node = ListNode(last_digit) l3.next = new_node if l1!=None: l1=l1.next if l2!=None: l2=l2.next l3=l3.next if carry>0: new_node = ListNode(carry) l3.next = new_node l3 = l3.next return dummy_head.next