Add Two Numbers in TypeScript

// Function to add two numbers represented by linked lists
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let head: ListNode | null = new ListNode(0); // Dummy head to start the result linked list
    let current = head; // Pointer to the current node in the result list
    let carry = 0; // Initialize carry to 0

    // Loop until both lists are exhausted and there is no carry
    while (l1 !== null || l2 !== null || carry > 0) {
        let sum = carry; // Start with carry

        // Add the value from l1 if it's not null
        if (l1 !== null) {
            sum += l1.val;
            l1 = l1.next; // Move to the next node in l1
        }

        // Add the value from l2 if it's not null
        if (l2 !== null) {
            sum += l2.val;
            l2 = l2.next; // Move to the next node in l2
        }

        carry = Math.floor(sum / 10); // Update carry for the next iteration
        current.next = new ListNode(sum % 10); // Create a new node with the digit part of sum
        current = current.next; // Move to the next node in the result list
    }

    return head.next; // Return the result list, excluding the dummy head
}

PrevNext