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

总结
边栏推荐
- Preprocessing - interpolation
- QT opens a file and uses QFileDialog to obtain the file name, content, etc
- ABAP dynamic inner table grouping cycle
- 再AD 的 界面顶部(菜单栏)创建常用的快捷图标
- ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
- 杭州电 3711 Binary Number
- Allow public connections to local Ruby on Rails Development Server
- 概率论公式
- 本机mysql
- 机械臂速成小指南(十):可达工作空间
猜你喜欢
随机推荐
QT opens a file and uses QFileDialog to obtain the file name, content, etc
【knife-4j 快速搭建swagger】
VHDL implementation of arbitrary size matrix addition operation
Kbone与小程序跨端开发的一些思考
Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)
easyui出口excel无法下载框弹出的办法来解决
Summer 2022 daily question 1 (1)
太方便了,钉钉上就可完成代码发布审批啦!
【安全攻防】序列化與反序列,你了解多少?
Codeworks 5 questions per day (1700 average) - day 7
VHDL implementation of single cycle CPU design
Antd Comment 递归循环评论
机器学习笔记 - 使用机器学习进行鸟类物种分类
Redis configuration and optimization of NoSQL
Arduino droplet detection
一些常用软件相关
NoSQL之Redis配置与优化
Mobile measurement and depth link platform - Branch
Baidu map JS development, open a blank, bmapgl is not defined, err_ FILE_ NOT_ FOUND
Que savez - vous de la sérialisation et de l'anti - séquence?