[LeetCode]:Add Two Numbers

【力扣Leetcode解题系列之0002. 两数之和Add Two Numbers:链表与数学运算的完美结合】 力扣2题"Add Two Numbers"是一道经典的链表加法问题,要求将两个逆序存储数字的链表相加并返回结果链表。解题关键在于模拟十进制加法过程,处理不同长度链表和进位问题。主要有两种解法:循环法和递归法。循环法通过遍历链表逐位相加,处理进位;递归法则通过递归调用处理后续节点和进位。两种方法的时间复杂度均为O(max(M,N)),空间复杂度为O(1)。题目考察了链表操作和数学运算的结合能力,是算法练习的典型范例。 阅读详情

Describe

  You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list

Input

  (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output

  7 -> 0 -> 8

Analyse

  题目的意思就是给两个单链表,然后将其中的整数相加,考虑进位,也就是题目Input中的4+6结果为10,所以结果为0然后向前面进1.因为要考虑的问题是两个链表的长度可能不相同,所以需要特别考虑一下。

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode *head = NULL,*t = NULL;
        int carry = 0;
        int val1 = 0,val2 = 0,val = 0;
        while(l1||l2){
            if(l1)
                val1 = l1->val;
            else
                val1 = 0;
            if(l2)
                val2 = l2->val;
            else
                val2 = 0;
            int result = val1 + val2 + carry;
            carry = result/10;
            val = result%10;
            ListNode *node = new ListNode(val);
            if(!head)
                head = node;
            if(t)
                t->next = node;
            t = node;
            if(l1)
                l1 = l1->next;
            if(l2)
                l2 = l2->next;
        }
        if(carry){
            ListNode *node = new ListNode(carry);
            t->next = node;
        }
        return head;
    }
};
OpenCV实战:如何用Debevec算法搞定相机响应函数(附完整代码) 本文详细介绍了如何使用OpenCV实现Debevec算法计算相机响应函数(CRF),并应用于HDR图像合成。通过完整的代码示例和工程实践问题解决方案,帮助开发者掌握从原理到实现的关键步骤,提升高动态范围成像和计算机视觉任务的处理能力。 阅读详情

相关推荐

Simulink中为Scope模块添加图例的方法

比如我要在Scope模块输出三轴加速度的数据,但三轴数据波形混杂在一起不太好看,此时就需要在Scope模块中添加图例来使波形看起来更加清晰明了。 注:我这里使用的Matlab版本为2019a 1.首先在simulink中打开,需要添加图例的Scope,如图示: 2.在Matlab,command窗口输入: >> set(0,'ShowHiddenHandles','On'); >> set(gcf,'menubar','figure'); 此时你会发现Scope窗口菜单栏多了好几

Kunfly的博客 1万+

【Java版】LeetCode 力扣第 2 题:两数相加 (Add Two Numbers)

题目描述 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 You are given two non-empty l

代码时光 752

MATLAB配置MinGW编译器的完整指南

本文提供了在Windows系统上为MATLAB配置MinGW编译器的完整指南。详细介绍了通过MATLAB附加功能管理器在线安装和手动离线安装两种核心方法,并重点说明了如何解决常见的“未找到支持的编译器”等错误。指南包含从版本检查、环境变量配置到最终使用mex命令验证的每一步,帮助用户顺利完成MATLAB与MinGW的集成,以支持C/C++代码编译。

weixin_29031057的博客 264

LeetCode:Add Two Numbers

Add Two Numbers - LeetCode

杂的文 639

HC-05蓝牙模块详细配置、连接与使用过程

用手按着模块上的按键,再给蓝牙模块上电。当蓝牙模块上的灯慢闪的时候就说明进入了配置模式了。在配置蓝牙的时候一定要将串口助手按这个要求配置:设置波特率 38400,数据位 8 位,停止位 1 位,无校验位,这是固定操作! 根据蓝牙的主从模式进行不同的设置,二者主要区别就在于AT+ROLE这个指令如果这里没返回OK可能有一下几种情况:如果正常返回OK,那就可以进行下一步了 配置蓝牙密码的时候,特别是配置HC05,密码必须加双引号"",否则不能正常设置!!!! 给从机模式蓝牙配置好之后,将蓝牙重

qq_51688022的博客 2万+

USB2.0信号完整性测试之眼图

名称线缆颜色引脚描述红色绿色白色GND黑色。

qq_53766840的博客 3286

JS斩杀LeetCode(2):Add Two Numbers

题目: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers a

清风的博客 2225

电池管理系统(BMS)软件:CATL BMS二次开发_(1).CATL BMS软件概述

CATL BMS软件的保护机制是确保电池组安全和可靠运行的关键部分。通过高精度的传感器和智能算法,BMS可以实时监测电池组的状态,及时采取保护措施。二次开发中,可以根据特定的应用需求,增加新的传感器、优化算法、扩展通信接口等,进一步提高系统的性能和可靠性。维护和扩展则是确保系统长期稳定运行的重要手段。希望以上内容对您理解CATL BMS软件的保护机制有所帮助。如果您有任何进一步的问题或需要更详细的解释,欢迎随时提问。

zhubeibei168的博客 1458

LeetCode题解:Add Two Numbers

Add Two Numbers You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers an

Magi Su的技术回收站 5462

SmartFusion从FPGA到ARM(一)——MSS_GPIO点灯

文章目录前言GPIO点灯 前言 GPIO点灯

whik1194的博客 5270

【AI编程】Vibe Coding 开发环境搭建与项目实战操作详解

Vibe Coding 开发环境搭建与项目实战操作详解

congge 7335

Leetcode1-50: 02, Add two numbers

Leetcode1-50: 02, Add two numbers问题描述解题思路代码实现复杂度分析分析 问题描述 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return

Y123iwantit的博客 213

分类预测 | MATLAB实现ELM极限学习机多特征分类预测(二分类)

分类预测 | MATLAB实现ELM极限学习机多特征分类预测(二分类)

机器学习之心的博客,关注并私信文章链接,获取对应文章源码和数据。 779

[LeetCode] 005: Add Two Numbers

[Problem]You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return i

1.02^365的成长裂变 3636

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Leetcode2: Add Two Numbers

这道题的难度是简单,说也简单,但也不简单 说不简单是因为,我为了这个审题的事儿,磨蹭了大半天 说简单是因为,审题审清楚了以后,写写也没多久 来看题目,他用一个链表的结构,来代表2个非负数,而非负数是链表中结点的数据元素,不过他是倒序的,也就是头结点是3和4 然后对应位数两两相加,输出一个也是链表类型的结果 接下来说觉得不简单的地方,因为,python里面是没有链表

bestallen的博客 857

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

LeetCode: Add Two Numbers

LeetCode: Add Two NumbersYou are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers

EmilSinclair4391的博客 777

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Leetcode: Add Two Numbers

题目连接:Add Two Numbers

no pains,no gains 567

leetcode: Add Two Numbers

题目: You are given two&nbsp;non-empty&nbsp;linked lists representing two non-negative integers. The digits are stored in&nbsp;reverse order&nbsp;and each of their nodes contain a single digit. Add the ...

时梦的博客 259

LeetCode算法题之2:Add Two Numbers

LeetCode之2:Add Two Numbers 问题描述: 将两个个位数数字组成的链表合并为一个,模拟加法器。 问题的陷阱: 在考虑进位问题时想的不全名,漏掉两个链表最终同时为空,而产生进位,导致最终少加一位数这一问题。 缺陷代码分析 /** * Definition for singly-linked list. * public class ListNode { * in...

veatheroe的博客 235

LeetCode 2: Add Two Numbers题解(Python)

Leetcode 2: Add Two Numbers 分类:Linked List 难度:Midium (M-) 描述: 给两个链表(linked list),链表元素是int形式,求两个链表代表的数的和 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. 链接: Add Two Numbers 思路: 此题稍微麻烦之处在于要用linked lis

Bourns_A的博客 424

LeetCode:Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return i...

啃梨的博客 166

Leetcode: Add Two Numbers

Add Two Numbers You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two

spirit_young的博客 426

【LeetCode】解题 2:Add Two Numbers

LeetCode解题思路 2:Add Two NumbersProblem 2: Add Two Numbers [medium]Solution修改过程 Problem 2: Add Two Numbers [medium] You are given two non-empty linked lists representing two non-negative integers. The d...

Fayedily的博客 205

leetcode : Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a link

u011212549的博客 315
上一篇: [LeetCode]:Two Sum
下一篇: [LeetCode]:Longest Substring Without Repeating Characters
潘建成
博客等级 码龄12年 139粉丝 120原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值