給你兩個 非空 的鍊錶,表示兩個非負的整數。它們每位數字都是按照 逆序 的方式儲存的,並且每個節點只能儲存 一位 數字。
請你將兩個數相加,並以相同形式返回乙個表示和的鍊錶。
你可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
# 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:
if l1 ==
none
:return l2
if l2 ==
none
:return l1
dummy = listnode(0)
#鍊錶的頭結點
p = dummy
carry =
0# 等長部分直接相加
while l1 and l2:
p.next
= listnode(
(l1.val + l2.val + carry)%10
) carry =
(l1.val + l2.val + carry)
//10
l1 = l1.
next
l2 = l2.
next
p = p.
next
# 不等長部分進行討論
if l2:
while l2:
p.next
= listnode(
(l2.val + carry)%10
) carry =
(l2.val + carry)
//10
l2 = l2.
next
p = p.
next
if l1:
while l1:
p.next
= listnode(
(l1.val + carry)%10
) carry =
(l1.val + carry)
//10
l1 = l1.
next
p = p.
next
# 如果相加之後最後一位是1的話
if carry ==1:
p.next
= listnode(1)
return dummy.
next
leecode python三數之和
題目 給乙個包含n 個整數的陣列nums,判斷nums中是否存在三個元素 a,b,c,使得三數相加 0?請找出所有滿足條件的不重複的三元組 例項 nums 1,0,1,2,1,4 滿足條件的三元組為 1,0,1 1,1,2 class solution def threesum self,nums ...
FFT NTT中檔題總結
被deepinc 怕了,把一些題放到這裡來 其實這道題放到中檔題也不太合適,個人感覺真的很難,機房裡好像都是頹的題解 因為期望的可加性,把每個點的貢獻單獨處理,即求期望深度 考慮 y 對 x 的貢獻 當且僅當 x y 的路徑上第乙個點就選 y y 才能成為 x 的祖先 所以 y 對 x 的貢獻就是 ...
leecode python簡單題 7 整數反轉
給你乙個 32 位的有符號整數 x 返回 x 中每位上的數字反轉後的結果。如果反轉後整數超過 32 位的有符號整數的範圍 231,231 1 就返回 0。假設環境不允許儲存 64 位整數 有符號或無符號 class solution def reverse self,x int int num 0 ...