当前位置:网站首页>【刷题记录】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;
}
}

总结
边栏推荐
- Kbone与小程序跨端开发的一些思考
- Using thread class and runnable interface to realize the difference between multithreading
- List interview common questions
- idea gradle lombok 报错集锦
- 【编码字体系列】OpenDyslexic字体
- 2022夏每日一题(一)
- My brave way to line -- elaborate on what happens when the browser enters the URL
- QT 项目 表格新建列名称设置 需求练习(找数组消失的数字、最大值)
- ABAP dynamic inner table grouping cycle
- 数据的存储
猜你喜欢
随机推荐
Storage of data
【安全攻防】序列化與反序列,你了解多少?
Docker部署Mysql8的实现步骤
MySQL的存储引擎
卡尔曼滤波-1
termux设置电脑连接手机。(敲打命令贼快),手机termux端口8022
Native MySQL
Redis configuration and optimization of NoSQL
[leetcode] 700 and 701 (search and insert of binary search tree)
map和set的实现
A 股指数成分数据 API 数据接口
The JSON format of the international area code of the mobile phone number is obtained with PHP
golang 压缩和解压zip文件
Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)
Termux set up the computer to connect to the mobile phone. (knock the command quickly), mobile phone termux port 8022
POJ培训计划2253_Frogger(最短/floyd)
What is the experience of maintaining Wanxing open source vector database
On file uploading of network security
HW-小记(二)
【mysql】mysql中行排序








