ZhuangER
9/30/2018 - 1:57 AM

[2. Add Two Numbers] #tags: leetcode

[2. Add Two Numbers] #tags: leetcode

/**
 * 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) {
    let header = new ListNode(null);
    let curPointer = header;
    header.next = curPointer;
    
    let nextDigit = 0;
    
    while(l1 || l2) {
        const a = l1 ? l1.val : 0;
        const b = l2 ? l2.val : 0;
        const sum = a + b + nextDigit;
        const curDigit = sum % 10;
        nextDigit = Math.floor(sum / 10);
        
        // the current pointer is one step ahead
        curPointer.next = new ListNode(curDigit);
        
        curPointer = curPointer.next;
        
        if (l1) {
            l1 = l1.next;
        }
        if (l2) {
            l2 = l2.next;   
        }
    }
    
    if (nextDigit > 0) {
        curPointer.next = new ListNode(nextDigit);
    }
    
    return header.next;
};