Difficulty: Medium
題目
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
翻譯
你將獲得兩個非空的鏈接列表,他們代表兩個非負值的整數. 這些數字以相反順序儲存,並且他們的每個節點都包含一個數字 將兩個數字相加並作為鏈接列表返回
您可以假設兩個數字不包含任何前導零,但數字0本身除外
範例
Example 1:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
Example 2:
1 | Input: l1 = [0], l2 = [0] |
Example 3:
1 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
解題思路
1.用新的link list儲存相加的結果並回傳
2.兩個相加有可能大於9,需考慮進位問題
3 要注意l1和l2有可能長度不同
Solution
Code 1 :
1 | var addTwoNumbers = function(l1, l2) { |
Code 2 :
1 | var addTwoNumbers = function(l1, l2) { |