<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]
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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法