当前位置:网站首页>做题笔记2(两数相加)
做题笔记2(两数相加)
2022-07-28 16:02:00 【竹林观月】
一、题目
二、思路
1
引入carry,默认为0。
2
当两个链表处于同一位的值都不为零时,两数相加再加上carry的值,若为个位数将该数赋予该节点;若为十位数,则还需将该数的十位赋予carry。
3
若两个链表中的一个在该节点处为空,则用0代替。
4
两链表都为空时,若carry的值不为零,需在尾部再插入carry的值。
三、用c++实现迭代法
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1!=0 || l2!=0)
{
int n1 =0;
if(l1!=0)
{
n1=l1->val;
}
int n2=0;
if(l2!=0)
{
n2=l2->val;
}
int sum = n1 + n2 + carry;
if (head==0)
{
head =tail = new ListNode(sum % 10);
}
else
{
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if (l1!=0)
{
l1 = l1->next;
}
if (l2!=0)
{
l2 = l2->next;
}
}
if (carry > 0)
{
tail->next = new ListNode(carry);
}
return head;
}
};
边栏推荐
- Implementation of paging
- 关于MIT6.828_HW9_barriers xv6 homework9的一些问题
- LeetCode-学会对无序链表进行插入排序(详解)
- IM即时通讯软件开发网络请求成功率的优化
- Signal shielding and processing
- Ansa secondary development - build ansa secondary development environment on Visual Studio code
- Outline and principle of structured design -- modularization
- Ruoyi's solution to error reporting after integrating flyway
- 微软100题-天天做-第11题
- Detailed record of steps to configure web server (many references)
猜你喜欢

Im im development optimization improves connection success rate, speed, etc

WSL+Valgrind+Clion

Quickly master kotlin set functions

Sort 2 bubble sort and quick sort (recursive and non recursive explanation)

Wake up after being repeatedly upset by MQ! Hate code out this MQ manual to help the journey of autumn recruitment

TCP handshake, waving, time wait connection reset and other records

有趣的 Kotlin 0x08:What am I

排序5-计数排序

nowcode-学会删除链表中重复元素两题(详解)

College students participated in six Star Education PHP training and found jobs with salaries far higher than those of their peers
随机推荐
egg(十九):使用egg-redis性能优化,缓存数据提升响应效率
parseJson
大学生参加六星教育PHP培训,找到了薪水远超同龄人的工作
LeetCode每日一练 —— 剑指Offer 56 数组中数字出现的次数
Multiple commands produce '... /xxx.app/assets.car' problem
asmlinkage的理解
Do you really understand CMS garbage collector?
PHP calculate coordinate distance
asp.net大文件分块上传断点续传demo
【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
重置grafana登录密码为默认密码
【从零开始学习SLAM】将坐标系变换关系发布到 topic tf
Is smart park the trend of future development?
智慧园区是未来发展的趋势吗?
队列的介绍与实现(详解)
排序1-插入排序与希尔排序
Optimization of network request success rate in IM instant messaging software development
给定正整数N、M,均介于1~10 ^ 9之间,N <= M,找出两者之间(含N、M)的位数为偶数的数有多少个
Nowcode- learn to delete duplicate elements in the linked list (detailed explanation)
Oracle table partition