这是悦乐书的第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)的更多相关文章

  1. [LeetCode] Add Two Numbers 两个数字相加

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  2. [LeetCode] 2. Add Two Numbers 两个数字相加 java语言实现 C++语言实现

    [LeetCode] Add Two Numbers 两个数字相加   You are given two non-empty linked lists representing two non-ne ...

  3. [LeetCode] 2. Add Two Numbers 两个数字相加

    You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...

  4. [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 ...

  5. LeetCode 2. 两数相加(Add Two Numbers)

    2. 两数相加 2. Add Two Numbers 题目描述 You are given two non-empty linked lists representing two non-negati ...

  6. [LintCode] Add Two Numbers 两个数字相加

    You have two numbers represented by a linked list, where each node contains a single digit. The digi ...

  7. [Swift]LeetCode2. 两数相加 | Add Two Numbers

    You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...

  8. LeetCode第[2]题(Java):Add Two Numbers (链表相加)——Medium

    题目难度:Medium 题目: You are given two non-empty linked lists representing two non-negative integers. The ...

  9. 2.两数相加(Add Two Numbers) C++

    第一想法是顺着题目的原因,将两链表分别转化为一个数字,再将数字相加,然后把结果转化为字符串,存到答案链表中.但是数据太大会溢出! 所以,要在计算一对数字的过程当中直接存储一个结果,注意结果大于9时进位 ...

随机推荐

  1. 菜鸟使用 centOS 安装 redis 并放入service 启动 记录

    1.下载redis: wget http://download.redis.io/releases/redis-2.8.17.tar.gz 若wget 不可用,请先安装wget yum install ...

  2. C# FormClosing FormClosed 区别详解

    FormClosing事件 在窗体关闭时,FormClosing事件发生.此事件会得到处理.从而释放与窗体相关的所有资源. 如果取消此事件,则窗体仍然保持打开状态. 当窗体显示为模式对话框时,单击“关 ...

  3. AI:IPPR的模式生成-学习/训练方式(基本结构)

    前言:        一个完备的模式识别系统,必然包含一个模式识别模型,此外还要附加一个评价模型,以及为了构建识别模型而构建的学习模型,并选择在学习模型中使用的学习方法. 否则  w=w 这样,)那样 ...

  4. java模拟Cookies登陆

    在使用java访问URL时,如果该URL需要身份验证,那么就不能够直接访问,因为没有登陆.那么,如何解决这个问题呢? 方法是使用java模拟登陆,登陆后记录下cookie信息,在下次发起请求时时将co ...

  5. luogu P2422 良好的感觉 单调栈

    Code: #include<bits/stdc++.h> #define maxn 1000000 #define ll long long using namespace std; v ...

  6. Ubuntu下解压(unzip)乱码的解决方法

    在Windows上压缩的文件,是以Windows系统默认编码中文来压缩文件.由于zip文件中没有声明其编码,所以linux上的unzip一般以默认编码解压,中文文件名会出现乱码. 通过unzip -- ...

  7. 04-Linux系统编程-第01天(文件IO、阻塞非阻塞)

    03-系统函数 系统编程章节大纲 1 文件I/O 2 文件系统 3 进程 4 进程间通信 5 信号 6 进程间关系 7 守护进程 8 线程 9 线程同步 10 网络基础 11 socket编程 12 ...

  8. 51nod1081 子段求和

    给出一个长度为N的数组,进行Q次查询,查询从第i个元素开始长度为l的子段所有元素之和. 例如,1 3 7 9 -1,查询第2个元素开始长度为3的子段和,1 {3 7 9} -1.3 + 7 + 9 = ...

  9. Mysql学习总结(12)——21分钟Mysql入门教程

    21分钟 MySQL 入门教程 目录 一.MySQL的相关概念介绍 二.Windows下MySQL的配置 配置步骤 MySQL服务的启动.停止与卸载 三.MySQL脚本的基本组成 四.MySQL中的数 ...

  10. 洛谷 P2483 BZOJ 1975 [SDOI2010]魔法猪学院

    题目描述 iPig在假期来到了传说中的魔法猪学院,开始为期两个月的魔法猪训练.经过了一周理论知识和一周基本魔法的学习之后,iPig对猪世界的世界本原有了很多的了解:众所周知,世界是由元素构成的:元素与 ...