Recursive solution in JavaScript. Feedback is appreciated!


  • 0
    J

    Here's my attempt at a recursive solution in JavaScript. Feedback is appreciated!

    const addTwoNumbers = (l1, l2) => {
        if (l1 === null && l2 === null) {
            return null;
        }
    
        let sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0);
        if (sum >= 10) {
            sum -= 10;
    
            let carry = 1;
            if (l1.next) {
                l1.next.val += carry;
            } else {
                l1.next = new ListNode(carry);
            }
        }
        
        let result = new ListNode(sum);
        result.next = addTwoNumbers(l1 ? l1.next : null, l2 ? l2.next : null);
    
        return result;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.