JavaScript expects the answer as an array (not a linked list)


  • 0
    I

    If you solve this problem in JavaScript and return a linked list it shows the expected value as an array so if you provide it a linked list it fails. Everything works fine if you make the output an array, but this is misleading and inconsistent with the other languages.


  • 0
    I

    Here is JavaScript solution returning an array (and the linked list return commented out)

    var addTwoNumbers = function(l1, l2) {
        
        // linked list version
        // var output = node = {};
        
        var output = [];
        var remainder = 0;
        
        while(l1 || l2) {
            var n1 = (l1 && l1.val) || 0;
            var n2 = (l2 && l2.val) || 0;
            
            var sum = n1 + n2 + remainder;
            if(sum > 9) {
                remainder = 1;
                sum -= 10;
            } else {
                remainder = 0;
            }
    
            // linked list version
            // node.val = sum;
            // node = node.next = {};
            
            output.push(sum);
            
            l1 = l1 ? l1.next : l1;
            l2 = l2 ? l2.next : l2;
        }
        
        if(remainder) {
            output.push(remainder);
        }
        
        return output;
    };
    

Log in to reply
 

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