[LeetCode] 445. Add Two Numbers II

Posted aaronliu1991

tags:

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

这题思路跟2很相似。唯一的不同点在于,2只是正向做加法,但是445是在逆向做加法。这题我的思路是先用stack存住两个list的nodes,然后pop出来的时候做加法。这样就不需要操心reverse linked list这件事了。

 1 /**
 2  * @param {ListNode} l1
 3  * @param {ListNode} l2
 4  * @return {ListNode}
 5  */
 6 var addTwoNumbers = function(l1, l2) {
 7     let s1 = [];
 8     let s2 = [];
 9     while (l1 !== null) {
10         s1.push(l1.val);
11         l1 = l1.next;
12     }
13     while (l2 !== null) {
14         s2.push(l2.val);
15         l2 = l2.next;
16     }
17 
18     let cur = new ListNode(0);
19     let sum = 0;
20     while (s1.length || s2.length) {
21         if (s1.length) {
22             sum += s1.pop();
23         }
24         if (s2.length) {
25             sum += s2.pop();
26         }
27         cur.val = sum % 10;
28         let head = new ListNode(Math.floor(sum / 10));
29         head.next = cur;
30         cur = head;
31         sum = Math.floor(sum / 10);
32     }
33     if (cur.val === 0) {
34         return cur.next;
35     } else {
36         return cur;
37     }
38 };

 

以上是关于[LeetCode] 445. Add Two Numbers II的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] 445. Add Two Numbers II

[LeetCode] 445. Add Two Numbers II

Leetcode刷题总结: 445. Add Two Numbers II

LeetCode 445. 两数相加 II(Add Two Numbers II)

LeetCode 445. 两数相加 II Add Two Numbers II (Medium)

LeetCode 445. 两数相加 II Add Two Numbers II (Medium)