当前位置:网站首页>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;
}
};
边栏推荐
- ROW_NUMBER()、RANK()、DENSE_RANK区别
- Vscade set multi line display of tab
- Analyzing more than 7million R & D needs, it is found that these eight programming languages are the most needed in the industry!
- SQL solves the problem of continuous login deformation holiday filtering
- LeetCode 5. 最长回文子串
- 结构体的内存对齐
- Data security industry series Salon (III) | data security industry standard system construction theme Salon
- Route service grid traffic through two-level gateway design
- LeetCode 6. Z 字形变换 (N字形变换)
- 历史上的今天:支付宝推出条码支付;分时系统之父诞生;世界上第一支电视广告...
猜你喜欢

路由模式:hash和history模式

JS learning notes - first acquaintance

Effectively use keywords to increase Amazon sales

电脑设备打印机驱动安装失败如何解决

Write your own CPU Chapter 11 - learning notes

Typescript array out of order output

TypeScript数组乱序输出

Rock PI Development Notes (II): start with rock PI 4B plus (based on Ruixing micro rk3399) board and make system operation

dried food! Understand the structural vulnerability of graph convolution networks

Multi task prompt learning: how to train a large language model?
随机推荐
绝对真理和相对真理思考
JS learning notes - operators
PCL least median square method fitting plane
Mathematical analysis_ Notes_ Chapter 6: Riemann integral of univariate function
Leetcode --- longest public prefix
Unity Json 编写
JS learning notes - process control
Seal Library - installation and introduction
数据安全产业系列沙龙(三)| 数据安全产业标准体系建设主题沙龙
Library management system (Shandong Agricultural University Curriculum Design)
路由模式:hash和history模式
Maui learning road (III) -- in depth discussion of winui3
(practice C language every day) the sum of the nearest three numbers
去除router-link中的下划线
mysql min() 求某条件下最小的值出现多个结果
Register as a harmonios developer and install deveco studio 3.0 beta2 for harmonios
MySQL calculates the data within the longitude and latitude range
学生选课系统(山东农业大学课程设计)
The difference and usage of calloc, malloc and realloc functions
结构体的内存对齐