您的位置:首页 > 编程语言 > Python开发

<LeetCode><Medium>2 Add Two Numbers

2015-11-20 23:06 597 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode