【算法训练】LeetCode#2 两数相加
一、描述
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
二、解题
循环遍历两个链表,并存储进位
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
returnNode = ListNode() # 返回链表
head = returnNode
# 如果l1为空则直接返回空数组
if l1 is None:
return l1
elif l2 is None:
return l2
else:
# 存储进位
num = 0
breakFlag = ""
while True:
if l1 is None and l2 is None:
breakFlag = "l1l2"
break
if l1 is None :
breakFlag = "l1"
break
if l2 is None:
breakFlag = "l2"
break
# 均不为空时,遍历
temp = l1.val + l2.val + num
# 计算进位
num = temp // 10
# 计算保留
temp = temp - num * 10
node = ListNode(temp)
returnNode.next = node
returnNode = returnNode.next
l1 = l1.next
l2 = l2.next
# 结束循环后,处理剩余
if breakFlag == "l1":
# 如果l1短
while l2 is not None:
# 均不为空时,遍历
temp = l2.val + num
# 计算进位
num = temp // 10
# 计算保留
temp = temp - num * 10
node = ListNode(temp)
returnNode.next = node
returnNode = returnNode.next
l2 = l2.next
if breakFlag == "l2":
# 如果l1短
while l1 is not None:
# 均不为空时,遍历
temp = l1.val + num
# 计算进位
num = temp // 10
# 计算保留
temp = temp - num * 10
node = ListNode(temp)
returnNode.next = node
returnNode = returnNode.next
l1 = l1.next
if num != 0:
node = ListNode(num)
returnNode.next = node
returnNode = returnNode.next
return head.next