1. 程式人生 > >Leetcode #2 Add two numbers

Leetcode #2 Add two numbers

理解 contains linked cti tin arr != 情況 目的

## 題目
>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.png](/img/bVXAi8)

Leetcode #2 Add two numbers