LeetCode.2-两个数字相加(Add Two Numbers)
这是悦乐书的第340次更新,第364篇原创
01 看题和准备
今天介绍的是LeetCode算法题中Medium级别的第1题(顺位题号是2)。给定两个非空链表,表示两个非负整数。 数字以相反的顺序存储,每个节点包含一个数字。将两个数字相加并将其作为链表返回。你可以假设这两个数字不包含任何前导零,除了数字0本身。例如:
输入:(2 -> 4 -> 3)+(5 -> 6 -> 4)
输出:7 -> 0 -> 8
说明:342 + 465 = 807。
本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。
02 第一种解法
计算链表的节点值之和,包含以下两种情况:
进位。两个节点值相加大于等于10后,会产生进位问题,需要将进位产生的数加到下一轮计算上去。如果是在最后一次计算产生进位,结果链表需要增加一个next节点。
两链表的长度不相等时,可能会有一个链表先遍历完节点,而另外一个还剩下许多节点没遍历,因此在遍历的循环条件处,判空是或的关系,直到两个链表的节点都遍历完,才结束循环。
在此解法中,我们使用一个新的链表(头节点值为0)作为结果链表,使用一个boolean类型的变量flag来当做是否有进位的标志。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode tem = l1;
ListNode tem2 = l2;
ListNode current = result;
boolean flag = false;
while (tem != null || tem2 != null) {
// 计算节点值之和,需要判空
int sum = (tem != null ? tem.val : 0) +
(tem2 != null ? tem2.val : 0);
// 有进位,节点值之和加1,flag变为false
if (flag) {
sum += 1;
flag = false;
}
// 节点值之和大于等于10,只保留个位数,flag变为true
if (sum >= 10) {
sum -= 10;
flag = true;
}
current.next = new ListNode(sum);
current = current.next;
if (tem != null) {
tem = tem.next;
}
if (tem2 != null) {
tem2 = tem2.next;
}
}
// 尾节点可能因进位而产生
if (flag) {
current.next = new ListNode(1);
}
return result.next;
}
03 第二种解法
思路和上面一样,只是将计算进位换了一种方式来实现,采用了取余和整除的方式来实现。
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode temp = result;
int count = 0;
while (l1 != null || l2 != null) {
int sum = (l1 == null ? 0 : l1.val) +
(l2 == null ? 0 : l2.val);
sum += count;
count = sum/10;
temp.next = new ListNode(sum%10);
temp = temp.next;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (count > 0) {
temp.next = new ListNode(count);
}
return result.next;
}
04 第三种解法
使用递归。
public ListNode addTwoNumbers3(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
helper(result, l1, l2, 0);
return result.next;
}
/**
* 递归方法
* @param result 结果链表
* @param l1
* @param l2
* @param carry 进位产生的数
*/
public void helper(ListNode result, ListNode l1, ListNode l2, int carry) {
if (l1 == null && l2 == null) {
return ;
}
int sum = (l1 == null ? 0 : l1.val) +
(l2 == null ? 0 : l2.val);
sum += carry;
carry = sum/10;
result.next = new ListNode(sum%10);
result = result.next;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
if (l1 == null && l2 == null && carry > 0) {
result.next = new ListNode(carry);
}
helper(result, l1, l2, carry);
}
05 第四种解法
对上面的递归方法,我们还可以再简化下,不借助额外的递归方法,以此方法本身做递归。
public ListNode addTwoNumbers4(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
int val = (l1 == null ? 0 : l1.val) +
(l2 == null ? 0 : l2.val);
ListNode result = new ListNode(val%10);
result.next = addTwoNumbers4(l1 == null ? null : l1.next,
l2 == null ? null : l2.next);
if (val >= 10) {
result.next = addTwoNumbers4(result.next, new ListNode(1));
}
return result;
}
06 小结
算法专题目前已连续日更超过六个月,算法题文章209+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。
以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!
LeetCode.2-两个数字相加(Add Two Numbers)的更多相关文章
- [LeetCode] Add Two Numbers 两个数字相加
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- [LeetCode] 2. Add Two Numbers 两个数字相加 java语言实现 C++语言实现
[LeetCode] Add Two Numbers 两个数字相加 You are given two non-empty linked lists representing two non-ne ...
- [LeetCode] 2. Add Two Numbers 两个数字相加
You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...
- [CareerCup] 2.5 Add Two Numbers 两个数字相加
2.5 You have two numbers represented by a linked list, where each node contains a single digit. The ...
- LeetCode 2. 两数相加(Add Two Numbers)
2. 两数相加 2. Add Two Numbers 题目描述 You are given two non-empty linked lists representing two non-negati ...
- [LintCode] Add Two Numbers 两个数字相加
You have two numbers represented by a linked list, where each node contains a single digit. The digi ...
- [Swift]LeetCode2. 两数相加 | Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...
- LeetCode第[2]题(Java):Add Two Numbers (链表相加)——Medium
题目难度:Medium 题目: You are given two non-empty linked lists representing two non-negative integers. The ...
- 2.两数相加(Add Two Numbers) C++
第一想法是顺着题目的原因,将两链表分别转化为一个数字,再将数字相加,然后把结果转化为字符串,存到答案链表中.但是数据太大会溢出! 所以,要在计算一对数字的过程当中直接存储一个结果,注意结果大于9时进位 ...
随机推荐
- VS2012快捷操作功能
VS2003用了6年,感情深厚,最近换工作刚刚接触VS2010,使用一个月感觉VS2010在人性化方面的功能实在是太强悍了,大大提高了写代码的效率,就如同魔兽世界里的快捷键操作一样,左手抚键右手摸鼠, ...
- AI:AI是什么?
古老的哲学对科学有永远的借鉴意义,科学上的咬文嚼字往往会让其丧失完备性. 一.AI是什么 你看起来它有多好,它就有多好.本质只能通过表象来描述,在色即是空的逻辑里,图灵测试也许是最精准的AI测试方式. ...
- Arduino控制DTH11模块
一.接线原理图 二.实物图 三.事例代码 下载 git clone https://github.com/adafruit/DHT-sensor-library.git 放到 arduino-1.6. ...
- (转)Jetty实战之 安装 运行 部署
http://blog.csdn.net/kongxx/article/details/7218767 本文地址:http://blog.csdn.NET/kongxx/article/details ...
- google浏览器 打印A4 最大宽度和高度px
width: 1563px;(max) + = 分页了 + = 分页了 + = 没有分页 / ViewBag.results[].Count)); <td width="15%&quo ...
- Coreldraw软件反盗版提示x8有优惠活动 cdr x8提示盗版怎么办?
CorelDRAW X8装不上,我的悲伤有这么大,或者比这还大一点...♥♥♥如果你遇到这样的断了网,卸了装,装了卸,然后再安装的...╮(-_-)╭这样的保存和另存为都点不了,不敢关电脑的亦或是这样 ...
- Vue: axios 请求封装及设置默认域名前缀 (for Vue 2.0)
1. 实现效果 以get方法向http://192.168.32.12:8080/users 发起请求.获取数据并进行处理 this.apiGet('/users', {}) .then((res) ...
- HTTP 状态码 301 和 302 详解及区别——辛酸的探索之路
转自:http://blog.csdn.net/grandpang/article/details/47448395 一直对http状态码301和302的理解比较模糊,在遇到实际的问题和翻阅各种资料了 ...
- 1016 部分A+B (15 分)
正整数 AAA 的“DAD_ADA(为 1 位整数)部分”定义为由 AAA 中所有 DAD_ADA 组成的新整数 PAP_APA.例如:给定 A=3862767A = 3862767 ...
- cent OS官网上下载老版本系统镜像的正确打开方式
当时的情况是这样的: 客户需要给服务器安装cent OS 7.3操作系统,我打开官网https://www.centos.org/,点击“GET CENTOS”——>“Minimal ISO”, ...