关闭

<LeetCode><Medium>2 Add Two Numbers

标签: pythonleetcode
251人阅读 评论(0) 收藏 举报
分类:

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

#Python27 168ms

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

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        num1=[l1]
        num2=[l2]
        while 1:
            if num1[-1].next is None:break
            num1.append(num1[-1].next)
        while 1:
            if num2[-1].next is None:break
            num2.append(num2[-1].next)
        num1=int("".join([str(n.val) for n in num1][::-1]))
        num2=int("".join([str(n.val) for n in num2][::-1]))
        nums=[ListNode(int(s)) for s in str(num1+num2)[::-1]]
        t=len(nums)
        nums[-1].next=None
        if len(nums)>1:
            for i in range(len(nums)-1):
                nums[i].next=nums[i+1]
        return nums[0]
            


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:101601次
    • 积分:2454
    • 等级:
    • 排名:第15010名
    • 原创:138篇
    • 转载:1篇
    • 译文:2篇
    • 评论:19条
    文章分类
    最新评论