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

总结
边栏推荐
- Quick completion guide of manipulator (10): accessible workspace
- 卡尔曼滤波-1
- [dpdk] dpdk sample source code analysis III: dpdk-l3fwd_ 001
- QT thread and other 01 concepts
- QT 打开文件 使用 QFileDialog 获取文件名称、内容等
- golang 压缩和解压zip文件
- Preprocessing - interpolation
- Machine learning notes - bird species classification using machine learning
- First understand the principle of network
- Kbone与小程序跨端开发的一些思考
猜你喜欢

Some thoughts on cross end development of kbone and applet

Do you choose pandas or SQL for the top 1 of data analysis in your mind?

Confirm the future development route! Digital economy, digital transformation, data This meeting is very important

Mobile measurement and depth link platform - Branch

PHP lightweight Movie Video Search Player source code
![[hcie TAC] question 3](/img/d2/38a7286be7780a60f5311b2fcfaf0b.jpg)
[hcie TAC] question 3

2022年上半年HIT行业TOP50

再AD 的 界面顶部(菜单栏)创建常用的快捷图标

Storage of data

【mysql】mysql中行排序
随机推荐
Storage of data
Kbone与小程序跨端开发的一些思考
idea gradle lombok 报错集锦
如何检测mysql代码运行是否出现死锁+binlog查看
List interview common questions
golang 压缩和解压zip文件
C task expansion method
It's too convenient. You can complete the code release and approval by nailing it!
手机号国际区号JSON格式另附PHP获取
The JSON format of the international area code of the mobile phone number is obtained with PHP
MySQL storage engine
ggplot 分面的细节调整汇总
Construction of Hisilicon universal platform: color space conversion YUV2RGB
Do you choose pandas or SQL for the top 1 of data analysis in your mind?
21. (article ArcGIS API for JS) ArcGIS API for JS rectangular acquisition (sketchviewmodel)
HW notes (II)
Free PHP online decryption tool source code v1.2
[security attack and Defense] how much do you know about serialization and deserialization?
VHDL implementation of single cycle CPU design
Native MySQL