[日常 LeetCode] 2. Add Two Numbers

  |   0 评论   |   0 浏览

  Q:
You are given twonon-emptylinked lists representing two non-negative integers. The digits are stored inreverse orderand 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:

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

  以下解答方式纯属抄的,尴尬的是好几天 没看懂题目
A:

 1# Definition for singly-linked list.
 2# class ListNode:
 3#     def __init__(self, x):
 4#         self.val = x
 5#         self.next = None
 6
 7class Solution:
 8    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
 9        c1=l1
10        c2=l2
11        c_val=''
12        c2_val=''
13        while c1:
14            c_val += str(c1.val)
15            c1=c1.next
16        while c2:
17            c2_val += str(c2.val)
18            c2=c2.next
19        c_val = c_val[::-1]
20        c2_val=c2_val[::-1]
21
22        added = int(c_val) + int(c2_val)
23
24        added =str(added)
25        added =added[::-1]
26
27        LL=[]
28        for i in added:
29
30            LL.append(int(i))
31
32
33        return LL
---------------------------------------------------------------
>> 博客地址:https://blog.mufengs.com
>> 邮箱地址:[email protected]
>> 微信帐号:Do8080
>> Github : https://github.com/mufengcoding
---------------------------------------------------------------