445. Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.1 题目要求不reverse ,所以转换成str求和,然后再转回ListNodetime O(n),space O(n)
【leetcode|【python3】leetcode 445. Add Two Numbers II (Medium)】You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
在discussion里看到一个回复说的隐患 :You cannot do this way, because, integer overflow occurs, if linked list is big enough. The main objective of linked list addition is to use for big integers.如果两个链表长一点,转成int就会超出int的范围。我觉得说的很有道理,所以虽然这种解法Accepted但是还不不太可取。
# 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
"""
a = '';
b = ''
while(l1):
a += str(l1.val)
l1 = l1.next
while(l2):
b += str(l2.val)
l2 = l2.next
c = str(int(a) + int(b))
l3 = ListNode(int(c[0]))
node = l3
for i in range(1,len(c)):
node.next = ListNode(int(c[i]))
node = node.next
return l3
2 虽然不能转成int 但还是可以先把val提出到容器中(如str或list)然后按位相加
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
a = [];
b = []
while(l1):
a.append(l1.val)
l1 = l1.next
while(l2):
b.append(l2.val)
l2 = l2.next
tag = 0
c = []
maxlen = max(len(a),len(b))
#对齐补0
if len(a) < maxlen:
for i in range(maxlen - len(a)):a.insert(0,0)
if len(b) < maxlen:
for i in range(maxlen - len(b)):b.insert(0,0)for i in range(0,maxlen):
sum = a[maxlen-i-1] + b[maxlen-i-1] + tag
tag = 1 if sum >= 10 else 0
c.insert(0,str(sum%10))
if tag == 1:
c.insert(0,1)
l3 = ListNode(c[0])
node = l3
for i in range(1,len(c)):
node.next = ListNode(int(c[i]))
node = node.next
node.next = None
return l3
推荐阅读
- 推荐系统论文进阶|CTR预估 论文精读(十一)--Deep Interest Evolution Network(DIEN)
- Python专栏|数据分析的常规流程
- Python|Win10下 Python开发环境搭建(PyCharm + Anaconda) && 环境变量配置 && 常用工具安装配置
- Python绘制小红花
- Pytorch学习|sklearn-SVM 模型保存、交叉验证与网格搜索
- OpenCV|OpenCV-Python实战(18)——深度学习简介与入门示例
- python|8. 文件系统——文件的删除、移动、复制过程以及链接文件
- 爬虫|若想拿下爬虫大单,怎能不会逆向爬虫,价值过万的逆向爬虫教程限时分享
- 分布式|《Python3网络爬虫开发实战(第二版)》内容介绍
- java|微软认真聆听了开源 .NET 开发社区的炮轰( 通过CLI 支持 Hot Reload 功能)