当前位置:网站首页>Sword finger offer II 025 Adding two numbers in a linked list
Sword finger offer II 025 Adding two numbers in a linked list
2022-06-25 12:59:00 【Small white yards fly up】
A word summary
First reverse the list , Then add and carry from the beginning .
subject
Given two Non empty linked list l1 and l2 To represent two nonnegative integers . The highest digit is at the beginning of the list . They store only one digit per node . Adding these two numbers will return a new linked list .
It can be assumed that in addition to numbers 0 outside , Neither of these numbers starts with zero .

link :https://leetcode.cn/problems/lMSNwu
Ideas
It's actually adding two numbers . But the normal calculation is to add the sum from right to left 、 carry , But using a linked list to represent a number , You can only calculate numbers from left to right . So first reverse the two linked lists , Then move the sum together , That's all right. .
solution : First reverse the list , Add the sum
Code
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode next = null;
int add = 0;
while (l1 != null || l2 != null) {
int sum = add;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
add = sum / 10;
ListNode current = new ListNode(sum % 10);
current.next = next;
next = current;
}
if (add != 0) {
ListNode current = new ListNode(add);
current.next = next;
return current;
}
return next;
}
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode pre = null;
ListNode next;
while (current != null) {
next = current.next;
current.next = pre;
pre = current;
current = next;
}
return pre;
}
边栏推荐
- Jenkins pipeline uses
- 二叉树之_哈夫曼树_哈弗曼编码
- It is extraordinary to make a move, which is very Oracle!
- 百度搜索稳定性问题分析的故事
- Render values to corresponding text
- 地理空间搜索:kd树的实现原理
- How to implement a high-performance load balancing architecture?
- Visual studio2019 link opencv
- PPT绘论文图之导出分辨率
- My first experience of go+ language -- a collection of notes on learning go+ design architecture
猜你喜欢
随机推荐
剑指Offer 第 2 天链表(简单)
更新pip&下载jupyter lab
list. replace, str.append
微信全文搜索技术优化
[flask tutorial] flask overview
Alibaba stability fault emergency handling process
爱可可AI前沿推介(6.25)
用include what you use拯救混乱的头文件
高性能负载均衡架构如何实现?
量化交易之回测篇 - 期货CTA策略策略(TQZFutureRenkoWaveStrategy)
PPT绘图之AI助力论文图
KVM 脚本管理 —— 筑梦之路
Spoken English - weak reading
3+1保障:高可用系统稳定性是如何炼成的?
英语口语 - 连读
1251- Client does not support authentication protocol MySql错误解决方案
First acquaintance with CANopen
Drawing cubes with Visio
【AI助力科研】loss曲线傻瓜式绘制
JS enter three integers a, B and C, and sort them from large to small (two methods)
![[转]以终为始,详细分析高考志愿该怎么填](/img/77/715454c8203d722e246ed70e1fe0d8.png)







