avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

445.Two numbersII

  2024-01-01        
字数统计: 316字   |   阅读时长: 1min

topic:

2023-07-03 (1).png
445.Two numbers

Thought:

I have been with yesterday’s question,Find by the way
What is deducted is a very strange oneprecompiled.listnode.ListNode,But mine is'__main__.ListNode'。
Because:Repeatedly defined$ListNode$
不反转Linkedof方法可能就是昨天of那种,转化为math做。
The code is still0x3fof
and昨天ofanswer法一样

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
new_head = self.reverseList(head.next)
head.next.next = head # Direct the next node to yourself
head.next = None # 断开指向下一个节点of连接,ensure最终Linkedof末尾节点of next Is an empty node
return new_head

# l1 and l2 为当前遍历of节点,carry Be in place
def addTwo(self, l1: Optional[ListNode], l2: Optional[ListNode], carry=0) -> Optional[ListNode]:
if l1 is None and l2 is None: # recursion边界:l1 and l2 都Is an empty node
return ListNode(carry) if carry else None # If you are in place,Just create an additional node
if l1 is None: # if l1 是空of,Then then l2 一定不Is an empty node
l1, l2 = l2, l1 # exchange l1 and l2,ensure l1 non empty,从而简化Code
carry += l1.val + (l2.val if l2 else 0) # 节点值andcarry加在一起
l1.val = carry % 10 # Each node saves a digital position
l1.next = self.addTwo(l1.next, l2.next if l2 else None, carry // 10) # carry
return l1

def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
l1 = self.reverseList(l1)
l2 = self.reverseList(l2) # l1 and l2 Reversal,Just become【2. Two numbers】Over
l3 = self.addTwo(l1, l2)
return self.reverseList(l3)
  • Python
  • answer
  • math
  • Linked
  • recursion
  • Stack

扫一扫,分享到微信

微信分享二维码
345. Voice letter in the reverse string
538.Convert the binary search tree to cumulative tree
目录
  1. 1. topic:
  2. 2. Thought:
  3. 3. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号