2. 两数相加(Add Two Numbers)
给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
- 每个链表中的节点数在范围
[1, 100]
内 0 <= Node.val <= 9
- 题目数据保证列表表示的数字不含前导零
题解一(python):
1 # Definition for singly-linked list.
2 # class ListNode:
3 # def __init__(self, val=0, next=None):
4 # self.val = val
5 # self.next = next
6 class Solution:
7 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
8 #取出两个链表的数值
9 str1 = ‘‘
10 while l1 is not None:
11 str1 += str(l1.val)
12 l1 = l1.next
13
14 str2 = ‘‘
15 while l2 is not None:
16 str2 += str(l2.val)
17 l2 = l2.next
18
19 #将两个链表的值相加求和
20 str3 = ‘‘
21 str3 = int(str1[::-1])+int(str2[::-1]) #倒序相加
22 str3 = [int(i) for i in str(str3)][::-1] # 倒序
23
24 # 创建链表,并以root为根节点
25 root = ListNode(str3.pop(0))
26 node = root
27 while str3 != []:
28 node.next = ListNode(str3.pop(0))
29 node = node.next
30
31 return root