当前位置:网站首页>【刷题记录】2. 两数相加
【刷题记录】2. 两数相加
2022-07-06 21:33:00 【InfoQ】
一、题目描述

- 每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
- 题目数据保证列表表示的数字不含前导零
二、思路分析:

- l1 就是[3,4] l2 就是[7,2] 链表中对应位置的相加,就是数字运算过程中,由低位向高位相加的一个过程。
- 如果相加有进位数时候,我们要记录进位数,并且在一次的运行中相加上这个进位数 就是上图中的1(tens)
- 然后把每次的结果存入到一个新的链表中 比如上图中结果为70 就是 [0,7]
三、代码实现
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 输出结果的链表
ListNode resultNode = new ListNode(0);
ListNode head = resultNode;
// 记录进位数
int carryNum = 0;
while (l1 != null || l2 != null){
// 判断两个链表中对应位置是否存在值 (可能连个链表位数不一致)
int num1 = l1 != null ? l1.val : 0;
int num2 = l2 != null ? l2.val : 0;
// 对应位置上的数字相加 以及加上进位数
int tmpnum = num1 + num2 + carryNum;
// 记录对应数字到链表
head.next = new ListNode(tmpnum % 10 );
//获取进位数
carryNum = tmpnum / 10;
head = head.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
// 如果最高位还有进位 补位。
if (carryNum > 0) head.next = new ListNode(carryNum);
return resultNode.next;
}
}

总结
边栏推荐
- 史上最全学习率调整策略lr_scheduler
- Hisilicon 3559 universal platform construction: RTSP real-time playback support
- Docker部署Mysql8的实现步骤
- UltraEdit-32 温馨提示:右协会,取消 bak文件[通俗易懂]
- QT 项目 表格新建列名称设置 需求练习(找数组消失的数字、最大值)
- One of oscp tools: dirsearch usage Encyclopedia
- MySQL storage engine
- Operational amplifier application summary 1
- 使用Thread类和Runnable接口实现多线程的区别
- Termux set up the computer to connect to the mobile phone. (knock the command quickly), mobile phone termux port 8022
猜你喜欢

浅谈网络安全之文件上传

Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)

idea gradle lombok 报错集锦

Tflite model transformation and quantification

【安全攻防】序列化與反序列,你了解多少?

cuda编程

QT 打开文件 使用 QFileDialog 获取文件名称、内容等

Some thoughts on cross end development of kbone and applet

Preprocessing - interpolation

Introduction to opensea platform developed by NFT trading platform (I)
随机推荐
什么是 CGI,什么是 IIS,什么是VPS「建议收藏」
Do you choose pandas or SQL for the top 1 of data analysis in your mind?
10 ways of interface data security assurance
Native MySQL
When QT uses qtooltip mouse to display text, the picture of the button will also be displayed and the prompt text style will be modified
golang 根据生日计算星座和属相
接口数据安全保证的10种方式
SSL certificate deployment
ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
使用 BR 恢复 GCS 上的备份数据
[leetcode] 450 and 98 (deletion and verification of binary search tree)
tflite模型转换和量化
API data interface of A-share index component data
Redis configuration and optimization of NoSQL
[leetcode] 700 and 701 (search and insert of binary search tree)
[security attack and Defense] how much do you know about serialization and deserialization?
Kotlin Android environment construction
PHP 实现根据概率抽奖
二进制、八进制、十六进制
[dpdk] dpdk sample source code analysis III: dpdk-l3fwd_ 001