leetcode 03. addTwoNumber

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WUUUSHAO/article/details/88244877

开始的话:
每天三道题,养成良好的思维习惯。
一位爱生活爱技术来自火星的程序汪

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

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

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

示例:

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

show my code

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        out = list()
        dummy_head = ListNode(0)
        current = dummy_head
        rest = 0
        while (l1 is not None) or (l2 is not None):
            p = l1.val if l1 is not None else 0
            q = l2.val if l2 is not None else 0

            current.next = ListNode((rest + p + q) % 10)
            current = current.next
            rest = (rest + p + q) // 10

            l1 = l1.next if l1 is not None else None
            l2 = l2.next if l2 is not None else None
        if rest > 0:
            current.next = ListNode(rest)

        return dummy_head.next

刚开始用 l i s t list 输出的结果,没注意到返回类型是 L i s t N o d e ListNode ,然后就发现自己忘记了哑节点这个概念,还是要多学多看。

谢谢

更多代码请移步我的个人 g i t h u b github ,会不定期更新。
本章代码见 c o d e code
欢迎关注

猜你喜欢

转载自blog.csdn.net/WUUUSHAO/article/details/88244877
03.