2. Add Two Numbers

Solved at: Jul 14, 2025 🇲🇽

//Warning, this is an ugly one:
  var addTwoNumbers = function (l1, l2) {
    function getSum(linkedList) {
        let arr = [];
        let node = linkedList;
        while (node !== null) {
            if (node === null) {
                return arr;
            }
            arr.unshift(node.val);
            node = node.next;
        }
        return BigInt(arr.join(""))
    }
    const result = (getSum(l1) + getSum(l2)).toString().split("");
    let i = 0;
    const length = result.length;
    let last = null;
    while (i < length) {
        let linkedList = {
            val: Number(result[i]),
            next: last
        }
        last = linkedList
        i++;
    }
    return last
};
//Warning, this is an ugly one:
var addTwoNumbers = function (l1, l2) {
    function getSum(linkedList) { // Converts linked list to a number
            let arr = [];
            let node = linkedList;
            while (node !== null) { // Traverse the linked list
                    if (node === null) { // Redundant check, honestly i can't remember why i wrote this lmao
                            return arr;
                    }
                    arr.unshift(node.val); // Add value to the front (reverse order)
                    node = node.next; // Move to next node
            }
            return BigInt(arr.join("")) // Join digits and convert to BigInt, this is because some cases can throw really big numbers
    }
    const result = (getSum(l1) + getSum(l2)).toString().split(""); // Add numbers, split into digits
    let i = 0;
    const length = result.length;
    let last = null;
    while (i < length) { // Build the result linked list
            let linkedList = {
                    val: Number(result[i]), // Current digit
                    next: last // Link to previous node
            }
            last = linkedList // Update last node
            i++;
    }
    return last // Return head of the new linked list
};