两数相加

题目描述

给出两个 非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字0之外,这两个数都不会以0开头。

我的解法

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: List
        :type l2: List
        :rtype: List
        """
        if l1 == None or l1 == None:
            return("Input error!")
            
        flag1 =  len(l1) != 1 and l1[0] != 0
        flag2 =  len(l2) != 1 and l2[0] != 0
        if flag1 and flag2:
            num1 = int(''.join([str(i) for i in l1]))
            num2 = int(''.join([str(i) for i in l2])) 
            re_num = num1 + num2
            result = [int(e) for e in list(str(re_num))][::-1]
            return result
        else:
            return("Input error!")


test = Solution()  
l1 = [0, 4, 2]
l2 = [4, 6, 5] 
result = test.addTwoNumbers(l1, l2

解决方案

使用链表ListNode进行求解
思路: 首先从最低有效位也就是列表 l 1 l_1 l1 l 2 l_2 l2的表头开始相加。由于每位数字都应当处于0-9范围内,我们计算两个数字的和时可能会出现“溢出”。例如,5 + 7 = 125+7=12,此时将当前位的数值设置为 22,并将进位 carry = 1带入下一次迭代。进位 carry必定是 0或 1,这是因为两个数字相加(考虑到进位)可能出现的最大和为 9 + 9 + 1 = 19

其他人的Python解法

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        re = ListNode(0)
        r=re
        carry=0
        while(l1 or l2):
            x= l1.val if l1 else 0
            y= l2.val if l2 else 0
            s=carry+x+y
            carry=s//10
            r.next=ListNode(s%10)
            r=r.next
            if(l1!=None):l1=l1.next
            if(l2!=None):l2=l2.next
        if(carry>0):
            r.next=ListNode(1)
        return re.next

python中ListNode数据结构

python数据结构之链表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值