python3兩數(shù)相加的實現(xiàn)示例
兩數(shù)相加
給你兩個 非空 的鏈表,表示兩個非負的整數(shù)。它們每位數(shù)字都是按照 逆序 的方式存儲的,并且每個節(jié)點只能存儲 一位 數(shù)字。
請你將兩個數(shù)相加,并以相同形式返回一個表示和的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個數(shù)都不會以 0 開頭。
示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 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)建一個新鏈表,新鏈表的頭部先設(shè)置為l1頭部和l2頭部之和。
2.遍歷兩個鏈表,只要有一個還沒有遍歷完就繼續(xù)遍歷
3.每次遍歷生成一個當(dāng)前節(jié)點cur的下一個節(jié)點,其值為兩鏈表對應(yīng)節(jié)點的和再加上當(dāng)前節(jié)點cur產(chǎn)生的進位
4.更新進位后的當(dāng)前節(jié)點cur的值
5.循環(huán)結(jié)束后,因為首位可能產(chǎn)生進位,因此如果cur.val是兩位數(shù)的話,新增一個節(jié)點
6.返回頭節(jié)點
由題目注釋可以看出listNode這個類是用來創(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
改進改進:增加了空間復(fù)雜度。本以為一方為None后直接把另一個鏈表連上就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
到此這篇關(guān)于python3兩數(shù)相加的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)python3兩數(shù)相加內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Django contenttypes 框架詳解(小結(jié))
這篇文章主要介紹了Django contenttypes 框架詳解(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08探索Python內(nèi)置數(shù)據(jù)類型的精髓與應(yīng)用
本文探索Python內(nèi)置數(shù)據(jù)類型的精髓與應(yīng)用,包括字符串、列表、元組、字典和集合。通過深入了解它們的特性、操作和常見用法,讀者將能夠更好地利用這些數(shù)據(jù)類型解決實際問題。2023-09-09總結(jié)python多進程multiprocessing的相關(guān)知識
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著python multiprocessing多進程的相關(guān)知識展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06