leetcode练习:2.Add Two Numbers

Posted 年糕君の勉强笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode练习:2.Add Two Numbers相关的知识,希望对你有一定的参考价值。

好吧,其实我的代码很冗杂 噗 其实也就是链表的基础知识。

/**
 * 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 res = null;
    var head = null;
    var q = l1;
    var p = l2;
    var cin = 0;
    while(q != null && p != null) {
        var value = q.val + p.val + cin;
        cin = 0;
        
        var temp = new ListNode(value%10);
        
        if(value >= 10) {
            cin = 1;
        }
        
        if(head == null){
            res = temp;
            head = res;
        }        
        else {
            res.next = temp;
            res = res.next;
        }
            
        q = q.next;
        p = p.next;
    }
    
    while(q != null){
        var value = q.val + cin;
        cin = 0;
        var temp = new ListNode(value % 10);
        if(value >= 10) {
            cin = 1;
        }
        res.next = temp;
        res = res.next;
        q = q.next;
    }
    
    while(p != null) {
        var value = p.val + cin;
        cin = 0;
        var temp = new ListNode(value % 10);
        if(value >= 10) {
            cin = 1;
        }
        res.next = temp;
        res = res.next;
        p = p.next
    }
    
    if(cin != 0){
        var temp = new ListNode(cin);
        res.next = temp;
        res = res.next;
    }
    
    return head;
};

 

以上是关于leetcode练习:2.Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 2. Add Two Numbers

2. 两个数相加 [leetcode 2: Add Two Numbers]

2. 两个数相加 [leetcode 2: Add Two Numbers]

LeetCode - 2 - Add Two Numbers

[leetcode][2] Add Two Numbers

[LeetCode]2. Add Two Numbers