题目2 两数相加
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
解题思路:
思想:
当某一统一性的规则随着循环而改变时,我们可以通过加减元素来使两个原本长度不同的数据,变成相同,进而统一情况,减少不必要的分别讨论。
代码:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
signal = 0 # 进位标志
elems = []
while l1 is not None and l2 is not None:
elem_0 = l1.val + l2.val + signal
signal = 0
if elem_0 >= 10:
elem_0 = elem_0 - 10
signal = 1
elems.append(elem_0)
if l1.next is None and l2.next is None:
if signal == 1:
elems.append(1)
if l1.next is None and l2.next is not None: # 在这里面追加元素 从而统一
l1.next = ListNode(0)
if l2.next is None and l1.next is not None:
l2.next = ListNode(0)
l1 = l1.next
l2 = l2.next
return elems