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

总结
边栏推荐
- 未来发展路线确认!数字经济、数字化转型、数据...这次会议很重要
- Unity3D在一建筑GL材料可以改变颜色和显示样本
- R data analysis: how to predict Cox model and reproduce high score articles
- 机器学习笔记 - 使用机器学习进行鸟类物种分类
- Kalman filter-1
- 【系统管理】清理任务栏的已删除程序的图标缓存
- codeforces每日5题(均1700)-第七天
- What is the experience of maintaining Wanxing open source vector database
- Calculation of time and space complexity (notes of runners)
- Arduino droplet detection
猜你喜欢

Redis configuration and optimization of NoSQL

链表面试常见题

【mysql】mysql中行排序

25. (ArcGIS API for JS) ArcGIS API for JS line modification line editing (sketchviewmodel)
![[leetcode] 700 and 701 (search and insert of binary search tree)](/img/b0/6aa9185f02fb1905fc59e6b329f7c3.jpg)
[leetcode] 700 and 701 (search and insert of binary search tree)

Web service performance monitoring scheme

Free PHP online decryption tool source code v1.2

List interview common questions

Implementation of map and set

2022夏每日一题(一)
随机推荐
Force buckle ----- path sum III
QT thread and other 01 concepts
idea gradle lombok 报错集锦
ABAP 动态内表分组循环
学习使用js把两个对象合并成一个对象的方法Object.assign()
Web service performance monitoring scheme
Class constant pool and runtime constant pool
One of oscp tools: dirsearch usage Encyclopedia
Some common software related
Introduction to opensea platform developed by NFT trading platform (I)
使用 Dumpling 备份 TiDB 集群数据到 GCS
ABAP 動態內錶分組循環
Arduino droplet detection
Binary, octal, hexadecimal
ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
ggplot 分面的细节调整汇总
如何检测mysql代码运行是否出现死锁+binlog查看
【mysql】mysql中行排序
QT 打开文件 使用 QFileDialog 获取文件名称、内容等
自适应非欧表征广告检索系统AMCAD