2. Add Two Numbers2. Add Two Numbers(两数相加)

问题描述

英文

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

中文

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

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

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

示例:

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

Solution

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        li1 = []
        li2 = []
        p1 = l1
        p2 = l2
        while p1 or p2:
            if p1:
                li1.append(p1.val)
                p1 = p1.next
            if p2:
                li2.append(p2.val)
                p2 = p2.next
        n1 = int(''.join(map(str,li1[::-1])))
        n2 = int(''.join(map(str,li2[::-1])))
        li = list(str(n1+n2))
        head = p = ListNode(li.pop()) # 单独处理头结点
        while li:
            q = ListNode(li.pop())
            p.next = q
            p = q
        return head

Submissions

执行用时 : 104 ms, 在Add Two Numbers的Python3提交中击败了99.94% 的用户

内存消耗 : 13.3 MB, 在Add Two Numbers的Python3提交中击败了0.95% 的用户