LeetCode 2 两数相加 Python

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807 
class Solution:
    def addTwoNumbers(self, l1, l2):
        temp1, temp2 = l1, l2
        t = 0#表示进位

        ans = temp1.val + temp2.val
        t = ans // 10
        ans = ans % 10
        res = ListNode(ans)


        temp3 = res
        while temp1.next != None and temp2.next != None:#两个链表均没有加完的时候
            temp1, temp2 = temp1.next, temp2.next
            ans = temp1.val + temp2.val + t#标水当前两数字相加的值
            t = ans // 10
            ans = ans % 10
            temp3.next = ListNode(ans)
            temp3 = temp3.next

        #此时两个链表至少有一个为空,为方便,均调整到temp1
        if temp2.next != None: temp1 = temp2
        while temp1.next !=  None:
            temp1 = temp1.next
            ans = temp1.val + t
            t = ans // 10
            ans = ans % 10
            temp3.next = ListNode(ans)
            temp3 = temp3.next

        if t > 0:
            temp3.next = ListNode(t)        

        return res

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值