16 May 2023 · filed under Coding challenge

LeetCode: Adding Two Numbers

pythonleetcodelinked-lists

Solution #1

from typing import Optional


def addTwoNumbers(l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
    """
    Adds two numbers represented as linked lists.

    Args:
        l1 (Optional[ListNode]): The head of the first linked list.
        l2 (Optional[ListNode]): The head of the second linked list.

    Returns:
        Optional[ListNode]: The head of the resulting linked list representing the sum.

    Examples:
        >>> l1 = ListNode(2)
        >>> l1.next = ListNode(4)
        >>> l1.next.next = ListNode(3)
        >>> l2 = ListNode(5)
        >>> l2.next = ListNode(6)
        >>> l2.next.next = ListNode(4)
        >>> result = addTwoNumbers(l1, l2)
        >>> while result:
        ...     print(result.val, end=' ')
        ...     result = result.next
        7 0 8
    """
    initial_node = current_node = ListNode()
    carry_over = 0
    while l1 or l2:
        if l1 is None:
            x = 0
            y = l2.val
            l2 = l2.next
        elif l2 is None:
            x = l1.val
            y = 0
            l1 = l1.next
        else:
            x, y = l1.val, l2.val
            l1, l2 = l1.next, l2.next

        # Creating new node
        _sum = x + y + carry_over
        current_node.next = ListNode(val=_sum % 10)
        
        # Setting up next iteration
        carry_over = 1 if _sum > 9 else 0
        current_node = current_node.next

    if carry_over > 0:
        current_node.next = ListNode(val=carry_over)
    
    return initial_node.next