問題描述
給出兩個 非空 的鏈表用來表示兩個非負的整數(shù)。其中,它們各自的位數(shù)是按照 逆序 的方式存儲的,并且它們的每個節(jié)點只能存儲 一位 數(shù)字。
如果,我們將這兩個數(shù)相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設(shè)除了數(shù)字 0 之外,這兩個數(shù)都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
求解
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
function ListNode(val) {
this.val = val
this.next = null
}
var addTwoNumbers = function(l1, l2) {
let dummy = new ListNode(0) // 設(shè)置鏈表開頭為0的節(jié)點
let cur = dummy
let carry = 0 // 進位
while (l1 != null || l2 != null) {
let d1 = l1 == null ? 0 : l1.val
let d2 = l2 == null ? 0 : l2.val
const sum = d1 + d2 + carry // 兩數(shù)對應(yīng)位和進位相加
carry = Math.floor(sum / 10) // 計算進位
cur.next = new ListNode(sum % 10)
cur = cur.next
if (l1 != null) l1 = l1.next
if (l2 != null) l2 = l2.next
}
if (carry > 0) cur.next = new ListNode(carry)
return dummy.next // return為0節(jié)點后的一個節(jié)點即為開始節(jié)點
}
執(zhí)行結(jié)果
執(zhí)行用時 :132 ms, 在所有 JavaScript 提交中擊敗了70.21%的用戶
內(nèi)存消耗 :38.6 MB, 在所有 JavaScript 提交中擊敗了80.88%的用戶
| 提交結(jié)果 | 執(zhí)行用時 | 內(nèi)存消耗 |
|---|---|---|
| 通過 | 132ms | 38.6MB |
更多前端資料請關(guān)注公眾號 【三分鐘熱度工程師】

qrcode.jpg
如果覺得寫得還不錯,可以關(guān)注gitbook小冊