美文网首页
[LeetCode]2、两数相加

[LeetCode]2、两数相加

作者: 河海中最菜 | 来源:发表于2019-07-27 10:14 被阅读0次

    题目描述

    给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

    如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

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

    示例:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807

    思路

    1.设置哑变量dummy、cur、当前和carray、第一个链表辅助结点p1、第二个链表辅助结点p2。

    1. while p1 or p2
      3.如果P1不空,则加入carray,如果p2不为空,则加入carray
      4.将carray % 10 作为节点值,carray // 10作为进位
      5.重复2步骤
      6.检查carray是否为1,如是,继续添加节点。
    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
        def addTwoNumbers(self, l1, l2):
            if not l1 and not l2:
                return None
            if not l1 or not l2:
                return l1 or l2
            dummy = ListNode(0)
            cur = dummy
            p1 = l1
            p2 = l2
            carray = 0
            while p1 or p2:
                if p1:
                    carray += p1.val
                    p1 = p1.next
                if p2:
                    carray += p2.val
                    p2 = p2.next
                cur.next = ListNode(carray % 10)
                cur = cur.next
                carray //= 10
            if carray == 1:
                cur.next = ListNode(1)
                cur = cur.next
            cur.next = None
            return dummy.next
    
    AC2

    相关文章

      网友评论

          本文标题:[LeetCode]2、两数相加

          本文链接:https://www.haomeiwen.com/subject/tjysrctx.html