Javascript


  • 0
    W
    /**
     * 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) {
        var currentL1 = l1
        var currentL2 = l2
        var carry = 0
        
        var returnNodeHead = null
        var returnNodeTail = null
        while(currentL1 || currentL2 || carry){
            var currentL1Val = currentL1
              ? currentL1.val
              : 0
            var currentL2Val = currentL2
              ? currentL2.val
              : 0
            var sum = currentL1Val + currentL2Val + carry
            var newNode = new ListNode(sum % 10)
            if(!returnNodeHead){
                returnNodeHead = newNode
            }
            else{
                returnNodeTail.next = newNode
            }
            
            returnNodeTail = newNode
            carry = Math.floor(sum / 10)
            
            currentL1 = currentL1 
              ? currentL1.next
              : null
              
            currentL2 = currentL2
              ? currentL2.next
              : null
        }
        
        return returnNodeHead
        
        
    };
    

Log in to reply
 

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