【LeetCode】445. Add Two Numbers II 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/add-two-numbers-ii/description/
题目描述
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.
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
题目大意
有两个链表,分别是正序的十进制数字。现在要求两个十位数字的和,要求返回的结果也是链表。
解题方法
先求和再构成列表
选择easy模式的话,可以直接先求出和,再构建链表。
这么做的前提是python中没有最大的整数,所以无论怎么着不会越界!
Python代码如下:
# 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 = ''
num2 = ''
while l1:
num1 += str(l1.val)
l1 = l1.next
while l2:
num2 += str(l2.val)
l2 = l2.next
add = str(int(num1) + int(num2))
head = ListNode(add[0])
answer = head
for i in range(1, len(add)):
node = ListNode(add[i])
head.next = node
head = head.next
return answer
使用栈保存节点数字
可以采用翻转后变成 Add Two Numbers 的题目,但是题目说了最好别那么做。那么可以使用一个栈来完成类似的操作。上一个题目的结果也是数字的倒序的,而这个题要求结果是正序,那么加的过程中采用头插法,一直向头部插入新的节点就好了。
步骤非常类似Add Two Numbers。
# 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
"""
stack1 = []
stack2 = []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
answer = None
carry = 0
while stack1 and stack2:
add = stack1.pop() + stack2.pop() + carry
carry = 1 if add >= 10 else 0
temp = answer
answer = ListNode(add % 10)
answer.next = temp
l = stack1 if stack1 else stack2
while l:
add = l.pop() + carry
carry = 1 if add >= 10 else 0
temp = answer
answer = ListNode(add % 10)
answer.next = temp
if carry:
temp = answer
answer = ListNode(1)
answer.next = temp
return answer
二刷的时候使用的C++的vector来存储的每个节点的值,然后再做的加法。每次构建新节点使用的头插法,所以结果同样是题目要求的倒序。
C++代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
vector<int> v1, v2;
while (l1) {
v1.push_back(l1->val);
l1 = l1->next;
}
while (l2) {
v2.push_back(l2->val);
l2 = l2->next;
}
const int M = v1.size(), N = v2.size();
int i1 = M - 1, i2 = N - 1;
int carry = 0;
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
while (i1 >= 0 || i2 >= 0 || carry) {
int add = (i1 >= 0 ? v1[i1] : 0) + (i2 >= 0 ? v2[i2] : 0) + carry;
carry = add >= 10 ? 1 : 0;
add %= 10;
ListNode* cur = new ListNode(add);
cur->next = dummy->next;
dummy->next = cur;
if (i1 >= 0)
--i1;
if (i2 >= 0)
--i2;
}
return dummy->next;
}
};
类似题目
2. Add Two Numbers
989. Add to Array-Form of Integer
日期
2018 年 2 月 26 日
2019 年 2 月 22 日 —— 这周结束了
【LeetCode】445. Add Two Numbers II 解题报告(Python & C++)的更多相关文章
- [LeetCode] 445. Add Two Numbers II 两个数字相加之二
You are given two linked lists representing two non-negative numbers. The most significant digit com ...
- LeetCode 445 Add Two Numbers II
445-Add Two Numbers II You are given two linked lists representing two non-negative numbers. The mos ...
- [leetcode]445. Add Two Numbers II 两数相加II
You are given two non-empty linked lists representing two non-negative integers. The most significan ...
- LeetCode 445. Add Two Numbers II (两数相加 II)
题目标签:Linked List 题目给了我们两个 数字的linked list,让我们把它们相加,返回一个新的linked list. 因为题目要求不能 reverse,可以把 两个list 的数字 ...
- LeetCode 445. Add Two Numbers II(链表求和)
题意:两个非空链表求和,这两个链表所表示的数字没有前导零,要求不能修改原链表,如反转链表. 分析:用stack分别存两个链表的数字,然后从低位开始边求和边重新构造链表. Input: (7 -> ...
- 445. Add Two Numbers II - LeetCode
Question 445. Add Two Numbers II Solution 题目大意:两个列表相加 思路:构造两个栈,两个列表的数依次入栈,再出栈的时候计算其和作为返回链表的一个节点 Java ...
- 【LeetCode】731. My Calendar II 解题报告(Python)
[LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...
- 【LeetCode】Pascal's Triangle II 解题报告
[LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...
- 【LeetCode】137. Single Number II 解题报告(Python)
[LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...
随机推荐
- 使用 Addressables 来管理资源
使用 Addressables 来管理资源 一.安装 打开Package Manager,在Unity Technologies的目录下找到Addressables,更新或下载. 二.配置 依次打开W ...
- C++ 数字分类
1012 数字分类 (20分) 输入格式: 每个输入包含 1 个测试用例.每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数.数字间 ...
- Docker学习(五)——Docker仓库管理
Docker仓库管理 仓库(Repository)是集中存放镜像的地方. 1.Docker Hub 目前Docker官方维护了一个公共仓库Docker Hub.大部分需求都可以通过 ...
- html框架frame iframe
框架 通过使用框架,你可以在同一个浏览器窗口中显示不止一个页面.没分HTML文档称作一个框架. 缺点: 开发人员必须同时跟踪更多的HTML文档 很难打印整张页面 框架结构标签(<frameset ...
- NSURLConnection和Runloop
- 1.1 涉及知识点(1)两种为NSURLConnection设置代理方式的区别 //第一种设置方式: //通过该方法设置代理,会自动的发送请求 // [[NSURLConnection alloc ...
- 【Linux】【Services】【SaaS】Docker+kubernetes(8. 安装和配置Kubernetes)
1. 概念 1.1. 比较主流的任务编排系统有mesos+marathon,swarm,openshift(红帽内部叫atom服务器)和最著名的kubernetes,居然说yarn也行,不过没见过谁用 ...
- Spring 文档汇总
Spring Batch - Reference Documentation Spring Batch 参考文档中文版 Spring Batch 中文文档 Table 2. JdbcCursorIte ...
- Maven的聚合工程(多模块工程)
在开发2个以上模块的时候,每个模块都是一个 Maven Project.比如搜索平台,学习平台,考试平台.开发的时候可以自己管自己独立编译,测试,运行.但如果想要将他们整合起来,我们就需要一个聚合工程 ...
- RabbitMQ,RocketMQ,Kafka 几种消息队列的对比
常用的几款消息队列的对比 前言 RabbitMQ 优点 缺点 RocketMQ 优点 缺点 Kafka 优点 缺点 如何选择合适的消息队列 参考 常用的几款消息队列的对比 前言 消息队列的作用: 1. ...
- python3约瑟夫环问题
问题描述:n个人围成一个圈,从第一个人开始数1,数到第k个出局,然后下一个人继续从1数,求出局人编号 思路:将所有人编号放到数组里,一个人出局后,下一个人加上k对数组长度求余,得出下一个要删除的编号. ...