- 作者:陳大魚頭
- 項目地址:ying-leetcode
- 碎碎念:Mmmmm,不定期刷leetcode,會以JS TS PY的形式輸出出來
題目描述
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
解題思路
其實這題比較簡單,無非是兩個鏈表之間同層級的數字相加,唯一要注意的就是如果相加之後數字大於10,需要往下一級+1,當前級數是個位的那個數字。基本也是一個循環可以解決的。再注意處理下,如果一個鏈表長度長於另一個鏈表時的邊界處理,其餘就沒啥了。
JS版
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = (l1, l2) => {
let l3 = null
let cache = 0
let tens = 0
while (l1 || l2) {
let total = 0
if (l1) {
let l1Head = l1.val
total += l1Head
l1 = l1.next
}
if (l2) {
let l2Head = l2.val
total += l2Head
l2 = l2.next
}
total += tens
if (total >= 10) {
total -= 10
tens = 1
} else {
tens = 0
}
let node = new ListNode(total)
if (cache) {
cache.next = node
cache = node
} else {
l3 = node
cache = l3
}
}
if (tens === 1) {
cache.next = new ListNode(1)
}
return l3
}
TS版
class ListNode {
val: number
next: ListNode | any
constructor(value: number) {
this.val = value
this.next = null
}
}
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = (l1: ListNode, l2: ListNode) => {
let l3: null | ListNode = null
let cache: ListNode | null = null
let tens: number = 0
while (l1 || l2) {
let total: number = 0
if (l1) {
let l1Head = l1.val
total += l1Head
l1 = l1.next
}
if (l2) {
let l2Head = l2.val
total += l2Head
l2 = l2.next
}
total += tens
if (total >= 10) {
total -= 10
tens = 1
} else {
tens = 0
}
let node = new ListNode(total)
if (cache) {
cache.next = node
cache = node
} else {
l3 = node
cache = l3
}
}
if (tens === 1) {
cache.next = new ListNode(1)
}
return l3
}
PY版
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = None
cache = 0
tens = 0
while l1 or l2:
total = 0
if l1:
l1Head = l1.val
total = total + l1Head
l1 = l1.next
if l2:
l1Head = l2.val
total = total + l1Head
l2 = l2.next
total = total + tens
if total >= 10:
total = total - 10
tens = 1
else:
tens = 0
node = ListNode(total)
if cache:
cache.next = node
cache = node
else:
l3 = node
cache = l3
if tens == 1:
cache.next = ListNode(1)
return l3
如果你喜歡探討技術,或者對本倉庫有任何的意見或建議,非常歡迎加魚頭微信好友一起探討,當然,魚頭也非常希望能跟你一起聊生活,聊愛好,談天說地。 魚頭的微信號是:krisChans95 也可以掃碼添加好友,備註“csdn”就行