您好,登錄后才能下訂單哦!
這篇文章主要介紹python3中如何實(shí)現(xiàn)兩數(shù)相加,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
給你兩個(gè) 非空 的鏈表,表示兩個(gè)非負(fù)的整數(shù)。它們每位數(shù)字都是按照 逆序 的方式存儲(chǔ)的,并且每個(gè)節(jié)點(diǎn)只能存儲(chǔ) 一位 數(shù)字。
請(qǐng)你將兩個(gè)數(shù)相加,并以相同形式返回一個(gè)表示和的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個(gè)數(shù)都不會(huì)以 0 開(kāi)頭。
示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋?zhuān)?42 + 465 = 807.
示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]
1.創(chuàng)建一個(gè)新鏈表,新鏈表的頭部先設(shè)置為l1頭部和l2頭部之和。
2.遍歷兩個(gè)鏈表,只要有一個(gè)還沒(méi)有遍歷完就繼續(xù)遍歷
3.每次遍歷生成一個(gè)當(dāng)前節(jié)點(diǎn)cur的下一個(gè)節(jié)點(diǎn),其值為兩鏈表對(duì)應(yīng)節(jié)點(diǎn)的和再加上當(dāng)前節(jié)點(diǎn)cur產(chǎn)生的進(jìn)位
4.更新進(jìn)位后的當(dāng)前節(jié)點(diǎn)cur的值
5.循環(huán)結(jié)束后,因?yàn)槭孜豢赡墚a(chǎn)生進(jìn)位,因此如果cur.val是兩位數(shù)的話(huà),新增一個(gè)節(jié)點(diǎn)
6.返回頭節(jié)點(diǎn)
由題目注釋可以看出listNode這個(gè)類(lèi)是用來(lái)創(chuàng)建鏈表的,默認(rèn)next=None,val=0.
Definition for singly-linked list.
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(l1.val+l2.val) current = head while l1.next or l2.next: l1 = l1.next if l1.next else ListNode() l2 = l2.next if l2.next!=None else ListNode() current.next = ListNode(l1.val+l2.val+current.val//10) current.val = current.val%10 current = current.next if current.val >= 10: current.next = ListNode(current.val//10) current.val = current.val%10 return head
改進(jìn)改進(jìn):增加了空間復(fù)雜度。本以為一方為None后直接把另一個(gè)鏈表連上就ok了。然后,就打臉了。
然后又加了while
> [9999] # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(l1.val+l2.val) current = head while l1.next and l2.next: l1 = l1.next l2 = l2.next current.next = ListNode(l1.val+l2.val+current.val//10) current.val = current.val%10 current = current.next if l1.next == None and l2.next : while l2.next: l2 = l2.next current.next= ListNode(l2.val+current.val//10) current.val = current.val%10 current = current.next current.next = l2.next elif l2.next == None and l1.next: while l1.next: l1 = l1.next current.next= ListNode(l1.val+current.val//10) current.val = current.val%10 current = current.next current.next = l2.next if current.val >= 10: current.next = ListNode(current.val//10) current.val = current.val%10 return head
以上是“python3中如何實(shí)現(xiàn)兩數(shù)相加”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。