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.nodeInput: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8git
難度中等.
這個題目注意一下是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; };