<LeetCode><Medium>2 Add Two Numbers

来源:互联网 发布:php quot 转成符号 编辑:程序博客网 时间:2024/05/16 06:00

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 = Noneclass 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