Add two numbers¶

The idea is:¶
1) Create a l3 LinkedList and Iterate over l1 and l2¶
2) Add node values of l1 and l2 (and retenue if there is one)¶
3) Take the rest of the division by 10 and store it to the current l3 node¶
4) Take the integer part of the division by 10 and keep it as retenue¶
5) Advance l1, l2 and l3¶
6) Add the remaining retenue to l3¶
7) Return l3¶
In [ ]:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
    retenue, l3 = 0, ListNode()
    head = l3
    while l1 or l2:
        # if l1 is not ended, add the value of its current node
        if l1:
            retenue += l1.val
            l1 = l1.next
            
        # if l2 is not ended, add the value of its current node
        if l2:
            retenue += l2.val
            l2 = l2.next
        
        # add the value to l3, note that the value is a digit hence take the rest of the division by 10
        l3.next = ListNode(int(retenue % 10))
        l3 = l3.next
        retenue = (retenue - l3.val) / 10 # update the retenue as next digit value
    
    # if a retenue remains then add anoter node
    if retenue:
        l3.next = ListNode(int(retenue))
        
    return(head.next)