Leetcode #2 Add two numbers

2017-10-30  本文已影响0人  wwzwwz

题目

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 contains 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


分析

难度中等.
这个题目注意一下是reverse order 意思就是 2 -> 4 -> 3分别是个位,十位,百位
并且l1 & l2的长度不一定是相同的.
解决这道题目的主要是理解两个数相加最大的是进1,不可能进2或者更大的.定义一个carry来记录不进位还是1就好了.

解法

var addTwoNumbers = function(l1, l2) {
    let carry = 0;
    let first = new ListNode();
    let l3 = first;
    
    while(l1 || l2 || carry) {  
    // carry 是为了检验如l1 {5} l2{5}这种情况,就是
    //  最高位要进位的那种
    //  假如不添加,那么 最高位要是进位的话不会被考虑进来.
    //  如果不明白可以把while里面的carry去掉 然后测试一下
        let sum = carry;
        if (l1 !== null) {
            sum += l1.val;
            l1 = l1.next;
        }
        if (l2 !== null) {
            sum += l2.val;
            l2 = l2.next;
        }
    
        if (sum > 9) {
            carry = 1;
            sum = sum-10;
        }
        else {
            carry = 0;
        }
        l3.next = new ListNode(sum);
        l3 = l3.next;
    }
    
    return first.next;
};
clipboard.pngclipboard.png
上一篇下一篇

猜你喜欢

热点阅读