【发布时间】:2021-08-24 21:14:12
【问题描述】:
我正在解决 LeetCode 问题2. Add Two Numbers:
给你两个非空链表,代表两个非负整数。数字以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加,并将总和作为链表返回。
您可以假设这两个数字不包含任何前导零,除了数字 0 本身。
我在其中一个测试用例中失败了,其中 l1 = [9,9,9,9,9,9,9] 和 l2 = [9,9,9,9]。我正在输出 [8,9,9,9,9,1],正确的输出是 [8,9,9,9,0,0,0,1]。我的python代码发布在下面。我很确定我的第一个 while 循环 (l1 and l2) 工作正常。我不知道在第二个循环 (while l1) 中我需要更改什么以获得正确的输出。
if l1 == [0] and l2 == [0]:
return ListNode()
if l1 == [0]:
return l2
if l2 == [0]:
return l1
carry = False
sum_num = ListNode()
head = sum_num
while l1 and l2:
temp = l1.val + l2.val
if carry:
temp += 1
carry = False
if temp >= 10:
carry = True
sum_num.val = temp % 10
if temp < 10: #changed these from an if because not triggering correctly because double if
sum_num.val = temp
l1 = l1.next
l2 = l2.next
if not l1 or not l2:
break
sum_num.next = ListNode()
sum_num = sum_num.next
while l1:
temp2 = l1.val
if carry:
temp2 += 1
carry = False
if temp2 >= 10:
carry = True
sum_num.val = temp % 10
if temp2 < 10:
sum_num.val = temp
l1 = l1.next
if not l1:
break
sum_num.next = ListNode()
sum_num = sum_num.next
while l2:
temp3 = l2.data
if carry:
temp3 += 1
carry = False
if temp3 >= 10:
carry = True
sum_num.val = temp % 10
if temp3 < 10:
sum_num.val = temp
l2 = l2.next
if not l2:
break
sum_num.next = ListNode()
sum_num = sum_num.next
if carry:
sum_num.val = 1
return head
【问题讨论】:
-
请编辑您的问题并将您的代码复制粘贴到代码框中,而不是屏幕截图。如果 we 可以复制粘贴您的代码,那么 us 会更容易提供帮助,而我们无法从图像中做到这一点。
-
您是否尝试过在 IDE 中编写代码并设置断点或添加打印语句以查看哪里出错了?另外,您指的是什么“第一个”循环?
-
在我看来,您在较短的数字而不是较长的数字末尾停止了第一个循环。
-
我会使用 itertools.zip_longest 和 fillvalue=0
标签: python linked-list