leetcode第二题addTwoNumbers
LeeSir 发表于 2015年10月30日 16:14

https://leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8

/**
 * 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 l3 = new ListNode();
    var node = l3;
    var sum = 0;
    while (l1 || l2 || sum !== 0) {
        sum += (l1 ? l1.val : 0) + (l2 ? l2.val : 0);
        node.val = sum % 10;
        l1 = l1 ? l1.next : null;
        l2 = l2 ? l2.next : null;
        sum = Math.floor(sum / 10);
        if (l1 || l2 || sum !== 0) {
            node.next = new ListNode();
            node = node.next;
        }
    }
    return l3;
};