Javascript Equivalent


  • 0
    M

    I've not seen anyone post a possible javascript solution for this problem, so I'll be the first to do it. It does run correctly to generate [7,0,8]. However in its current state, Leetcode will not accept it as a solution due to the while statement evaluation being performed and evaluation of l1, l2 to advance to the next block in their lists...

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var addTwoNumbers = function(l1, l2) {
        /* This javascript code was revised from Java code at discuss.leetcode.com/topic/6220/my-accepted-java-solution */
            var prev = new ListNode();
            var head = prev;
            var carry = 0;
            var hasCarried = 0;
            while (l1 != null || l2 != null) {
                var cur = new ListNode();
                if (parseInt(carry) === 1) { hasCarried = 1; }
                var sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
                carry = sum / 10;
                if (parseInt(carry) === 1) { cur.val = 0; } else { cur.val = sum; }
                prev.next = cur;
                prev = cur;
                
                if (hasCarried === 1) { carry = 0; hasCarried = 0; }
                l1 = (l1 == null) ? l1 : l1.next;
                l2 = (l2 == null) ? l2 : l2.next;
            }
            /* head.next being returned to skip over the undefined for the starting empty node so that [7,0,8] is returned */
            return head.next;
    };
    

Log in to reply
 

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