彻头彻尾弄懂 LeetCode 2. 两数相加
LeetCode上此题用python的解法并不多,写得详细的也不多。
1. 原题
https://leetcode-cn.com/problems/add-two-numbers/
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
2. 题解
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:
dummy = curr = ListNode()
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = x + y + carry
curr.next = ListNode(sum % 10)
curr = curr.next
carry = sum // 10
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry:
curr.next = ListNode(carry)
return dummy.next
n1 = ListNode(2)
n2 = ListNode(4)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
n11 = ListNode(5)
n22 = ListNode(6)
n33 = ListNode(4)
n11.next = n22
n22.next = n33
solution = Solution()
dummy = solution.addtwonumbers(n1, n11)
print(dummy)
while dummy:
print(dummy.val)
dummy = dummy.next
3. 分块分析
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
n1 = ListNode(2)
n2 = ListNode(4)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
通过节点构建链表参考博客https://blog.csdn.net/qq_30815237/article/details/90750349
def addtwonumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = curr = ListNode()
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = x + y + carry
curr.next = ListNode(sum % 10)
curr = curr.next
carry = sum // 10
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry:
curr.next = ListNode(carry)
return dummy.next
此题的解法参考力扣解法https://leetcode-cn.com/problems/add-two-numbers/solution/jian-dan-yi-dong-javacpythonjs-pei-yang-y2w6g/
博主刚好看到以上2篇博客,将其整合,并将最后的测试结果打印。如有侵权,联系本人删除。欢迎转发,转发请注明出处https://blog.csdn.net/qq_40630902?spm=1010.2135.3001.5421
|