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

总结
边栏推荐
- 二叉搜索树的实现
- 25. (ArcGIS API for JS) ArcGIS API for JS line modification line editing (sketchviewmodel)
- A 股指数成分数据 API 数据接口
- Operational amplifier application summary 1
- PHP lightweight Movie Video Search Player source code
- QT 使用QToolTip 鼠标放上去显示文字时会把按钮的图片也显示了、修改提示文字样式
- Implementation steps of docker deploying mysql8
- Probability formula
- [leetcode]Spiral Matrix II
- Implementation of binary search tree
猜你喜欢

Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)
Implementation steps of docker deploying mysql8

How to detect whether the MySQL code runs deadlock +binlog view

复杂因子计算优化案例:深度不平衡、买卖压力指标、波动率计算

What is the experience of maintaining Wanxing open source vector database

What is Ba? How about Ba? What is the relationship between Ba and Bi?

Adaptive non European advertising retrieval system amcad

R data analysis: how to predict Cox model and reproduce high score articles

Que savez - vous de la sérialisation et de l'anti - séquence?

2022年上半年HIT行业TOP50
随机推荐
数据的存储
25. (ArcGIS API for JS) ArcGIS API for JS line modification line editing (sketchviewmodel)
[leetcode] 450 and 98 (deletion and verification of binary search tree)
QT item table new column name setting requirement exercise (find the number and maximum value of the array disappear)
链表面试常见题
Adaptive non European advertising retrieval system amcad
codeforces每日5题(均1700)-第七天
海思万能平台搭建:颜色空间转换YUV2RGB
什么是 BA ?BA怎么样?BA和BI是什么关系?
10 ways of interface data security assurance
Native MySQL
Top 50 hit industry in the first half of 2022
Hongmi K40S root gameplay notes
leetcode:面试题 17.24. 子矩阵最大累加和(待研究)
PHP implements lottery according to probability
Calculation of time and space complexity (notes of runners)
cuda编程
C task expansion method
如何编写一个程序猿另一个面试官眼前一亮的简历[通俗易懂]
Machine learning notes - bird species classification using machine learning