LeetCode: Adding Two Numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
0%