
【leedcode】0002. 鏈數之和
給定兩個 非空 的鏈表用來表示兩個非負的整數(即標題中據說的鏈數定義),其中,它們各自的位數是按照 逆序 的方式存盤的,并且它們的每個節點只能存盤 一位 數字,
如果,我們將這兩個數相加起來,則會回傳一個新的鏈表來表示它們的和,
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭,
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
class Node(object):
def __init__(self, x=None, Next=None):
self.val = x
self.next = Next
def __repr__(self):
return f'{self.val}->{self.next}'
class List(object):
def __init__(self, node=None):
self.head = node
def __repr__(self):
return f'[{self.head}]'
def build(self, num):
head = None
for i in str(num):
head = Node(int(i), head)
self.head = head
return self
@property
def length(self):
ret,ptr = 0,self.head
while ptr:
ptr = ptr.next
ret += 1
return ret
@property
def value(self):
ret,base,ptr = 0,1,self.head
while ptr:
ret += ptr.val * base
ptr = ptr.next
base *= 10
return ret
def add(self, other):
ret = List()
if self.length>other.length:
ret.build(self.value)
ptr1,ptr2 = ret.head,other.head
else:
ret.build(other.value)
ptr1,ptr2 = ret.head,self.head
carry = 0
while ptr1:
try: tmp = ptr2.val
except: tmp = 0
carry,ptr1.val = divmod(ptr1.val+tmp+carry,10)
ptr1 = ptr1.next
try: ptr2 = ptr2.next
except: pass
if carry:
ptr = ret.head
while ptr:
if not ptr.next:
ptr.next = Node(1)
break
ptr = ptr.next
return ret
if __name__ == '__main__':
L1,L2 = List(),List()
n1,n2 = 342,465
L1.build(n1)
L2.build(n2)
L3 = L1.add(L2)
L4 = L2.add(L1)
print(L1,L2,L3,L4,sep='\n')
print(L1.value,L2.value,L3.value,L4.value,sep='\n')
n1,n2 = 3,999
L1.build(n1)
L2.build(n2)
L3 = L1.add(L2)
L4 = L2.add(L1)
print(L1,L2,L3,L4,sep='\n')
print(L1.value,L2.value,L3.value,L4.value,sep='\n')
代碼這樣寫的好處是兩個加數都保持原來的值,網上好多例子兩數加完之后self本身也等于兩數之和了,另外,加上方法和屬性_repr__(),build(),.length,.value是為了方便檢查和創建單鏈表,
還有在逐位相加時,進位和該位上去掉進位的和用函式divmod來表達也非常簡捷有效,
代碼運行結果如下:
[2->4->3->None]
[5->6->4->None]
[7->0->8->None]
[7->0->8->None]
342
465
807
807
[3->None]
[9->9->9->None]
[2->0->0->1->None]
[2->0->0->1->None]
3
999
1002
1002

歡迎加入“派森特給站”社區!https://bbs.csdn.net/forums/PythonTogether
https://bbs.csdn.net/forums/PythonTogether
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/353391.html
標籤:其他
下一篇:程式的環境和預處理
