###### tags: `leetcode`, `javascript`
# 【LeetCode】Javascript - #2 Add Two Numbers
---
### 題目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
---
### 大概翻譯:
給您兩個非空鏈表,表示兩個非負整數。 數位按相反順序存儲,每個節點包含一個數位。 將這兩個數位相加,並將總和作為鏈表返回。
您可以假設這兩個數位不包含任何前導零,除了數位0本身。
---
例如:
```javascript=
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Input: l1 = [0], l2 = [0]
Output: [0]
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
```
---
```javascript=
var addTwoNumbers = function(l1, l2) {
// 先創建一個節點,因為需要用它來做指向
let headNode = new ListNode();
// 跟踪當前節點,以便我們可以輕鬆地在末尾添加新節點
let currNode = headNode;
// 根據上一次迴圈結果,取得1或是0的值
let carry = 0;
// while (l1 != null || l2 != null || carry != 0)
while (l1 || l2 || carry) {
let sum = carry;
if (l1) {
sum += l1.val;
l1 = l1.next;
}
if (l2) {
sum += l2.val;
l2 = l2.next;
}
if (sum >= 10) {
// 如果總和是2位數,將carry=1帶到下一次迴圈
carry = 1;
sum -= 10;
} else {
carry = 0;
}
// 將新的節點代入解答中
currNode.next = new ListNode(sum);
// 推進當前的節點
currNode = currNode.next;
}
return headNode.next;
};
```

---
*新手工程師的筆記,純粹記錄學了些啥東西
如果有前輩高人讀了我的文,文中有任何錯誤再麻煩指教指教*