当前位置:网站首页>LeetCode 2. 两数相加
LeetCode 2. 两数相加
2022-07-02 13:15:00 【_刘小雨】
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ret = new ListNode(0);
ListNode* cur = ret;
int sum = 0;
while(1)
{
if(l1 != nullptr)
{
sum += l1->val;
l1 = l1->next;
}
if(l2 != nullptr)
{
sum += l2->val;
l2 = l2->next;
}
cur->val = sum % 10;
sum /= 10;
if(l1 != nullptr || l2 != nullptr || sum)
cur = (cur->next = new ListNode(0));
else
break;
}
return ret;
}
};
边栏推荐
- OSPF - detailed explanation of NSSA area and full NSSA area (including configuration command), LSA type 7 lsa-7
- JS learning notes - process control
- Practice of constructing ten billion relationship knowledge map based on Nebula graph
- 历史上的今天:支付宝推出条码支付;分时系统之父诞生;世界上第一支电视广告...
- LeetCode 1. 两数之和
- Yyds dry goods inventory # look up at the sky | talk about the way and principle of capturing packets on the mobile terminal and how to prevent mitm
- Aike AI frontier promotion (2.15)
- 数据安全产业系列沙龙(三)| 数据安全产业标准体系建设主题沙龙
- (practice C language every day) the sum of the nearest three numbers
- TCP拥塞控制详解 | 2. 背景
猜你喜欢
关于mysql安装的一些问题
The login box of unity hub becomes too narrow to log in
Original God 2.6 server download and installation tutorial
曆史上的今天:支付寶推出條碼支付;分時系統之父誕生;世界上第一支電視廣告...
[fluent] dart data type number type (DART file creation | num type | int type | double type | num related API)
dried food! Understand the structural vulnerability of graph convolution networks
Yyds dry inventory company stipulates that all interfaces use post requests. Why?
Maui学习之路(三)--Winui3深入探讨
Vscode设置标签页多行显示
mysql数据库mysqldump为啥没有创建数据库的语句
随机推荐
通过两级网关设计来路由服务网格流量
路由模式:hash和history模式
ROW_NUMBER()、RANK()、DENSE_RANK区别
AWS云主机扩容
理想之光不灭
Leetcode -- number of palindromes
Data Lake (11): Iceberg table data organization and query
Unity Json 编写
What is Amazon keyword index? The consequences of not indexing are serious
Solve * * warning * *: your ApplicationContext is unlikely to start due to a @componentscan of the defau
关于mysql安装的一些问题
虚假的暑假
SQL solves the problem of continuous login deformation holiday filtering
False summer vacation
How to use stustr function in Oracle view
JS learning notes - first acquaintance
(practice C language every day) the sum of the nearest three numbers
JS learning notes - variables
Maui learning road (III) -- in depth discussion of winui3
外企高管、连续创业者、瑜伽和滑雪高手,持续迭代重构的程序人生