Skip to content

Latest commit

 

History

History
68 lines (49 loc) · 1.85 KB

445-add-two-numbers-ii.md

File metadata and controls

68 lines (49 loc) · 1.85 KB

445. Add Two Numbers II - 两数相加 II

给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

 

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

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7

题目标签:Linked List

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 212 ms 6.7 MB
# 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
        """
        if l1 is None: return l2
        if l2 is None: return l1
        a1 = []
        while l1 and l1.val is not None:
            a1.append(str(l1.val))
            l1 = l1.next
        a2 = []
        while l2 and l2.val is not None:
            a2.append(str(l2.val))
            l2 = l2.next
        s = list(map(int, list(str(int(''.join(a1)) + int(''.join(a2))))))
        res = p = ListNode(None)
        for si in s:
            p.next = ListNode(si)
            p = p.next
        return res.next