2. Add Two Numbers

LeetCode --- 2. Add Two Numbers 解题报告 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 and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

第一次都错了题,以为链表大数字都是逆置的,耽误我半天时间。

/**
 * 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) {
        if(l1 == NULL || l2 == NULL)
            return NULL;

        ListNode* p1 = l1;
        ListNode* p2 = l2;

        ListNode* head;
        ListNode** pp = &head;
        int carry = 0;
        while(p1 != NULL && p2 != NULL) {
            int num = p1->val + p2->val + carry;
            *pp = new ListNode(num % 10);
            pp = &((*pp)->next);
            carry = num / 10;
            p1 = p1->next;
            p2 = p2->next;
        }

        while(p1 != NULL) {
            int num = p1->val + carry;
            *pp = new ListNode(num % 10);
            pp = &((*pp)->next);
            carry = num / 10;
            p1 = p1->next;
        }
        while(p2 != NULL) {
            int num = p2->val + carry;
            *pp = new ListNode(num % 10);
            pp = &((*pp)->next);
            carry = num / 10;
            p2 = p2->next;
        }

        if(carry != 0) 
            *pp = new ListNode(carry);

        return head;
    }
};

 
the second clear solution:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(l1 == NULL || l2 == NULL)
            return NULL;

        ListNode* head;
        ListNode** pp = &head;
        int carry = 0;
        while(l1 != NULL || l2 != NULL || carry != 0) {
            int num = (l1 != NULL ? l1->val : 0) + (l2 != NULL ? l2->val : 0) + carry;
            *pp = new ListNode(num % 10);
            pp = &((*pp)->next);
            carry = num / 10;
            l1 = l1 != NULL ? l1->next : l1;
            l2 = l2 != NULL ? l2->next : l2;
        }
        return head;
    }
};
[LeetCode]--2. 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 linke 阅读详情

相关推荐

09、Flutter FFI Dart Native API

本文介绍了 Dart Native API 的基本用法,解决了 Dart 与 C 异步通讯的问题

eieihihi的专栏 4403

LeetCode 2. Add Two Numbers(C++)

使用了O(1)的额外空间,思路是将两个链表遍历并合并,合并过程中不断计算进位,如果计算到最后一次加法仍有进位(可能是两个链表对应位置值相加产生进位或者上一次的进位加本次值又产生进位),那么需要加一个值为1的新结点。 这种思路的优点是空间复杂度小,缺点是实现比较复杂(跟借助一个额外的数组和链表相比)。 /** * Definition for singly-linked list. * st

赞美月亮的专栏 1436

modbus

从机地址 功能码 起始地址高位 起始地址低位 数量高位 数量低位 字节数 0001H高位 0001H低位 0002H高位 0002H低位 CRC高位 CRC低位。每个输入寄存器的长度为2个字节。其中,CDH对应线圈0013H到001AH的内容,01H对应线圈001B到001CH的内容,未使用位用0填充。从机地址 功能码 起始地址高位 起始地址低位 寄存器数量高位 寄存器数量低位 CRC高位 CRC低位。从机地址 功能码 起始地址高位 起始地址低位 寄存器数量高位 寄存器数量低位 CRC高位 CRC低位。

lunhuicnm的博客 9765

LeetCode 2.Add Two Numbers 两数相加 Python3 三种解法

LeetCode 2.Add Two Numbers 两数相加 Python3 由于做提前连链表是怎么实现的都不知道所以补了点课。 Single Linked List 代码来自这位兄台 pasilo https://blog.51cto.com/13047263/2070815 内容理解我看的知乎 如何更好的理解链表 以下代码和LeetCode上面的链表稍微有些许不同,那个里面链表和链表上面的节...

Aixoum is Me 1290

从零构建AI Agent集群:Docker Compose与Nginx部署实战

在AI应用开发领域,微服务架构和容器化部署已成为提升开发效率和系统可维护性的关键技术。Docker Compose作为容器编排工具,能够将多个独立服务(如Node.js、Python应用)及其依赖(数据库、缓存)封装在隔离环境中,并通过统一配置文件定义服务间的网络与依赖关系,实现一键启停。Nginx作为反向代理,则提供了统一的网络入口、请求路由和负载均衡能力,是构建高可用Web应用的基石。这种组合技术方案的价值在于,它能将复杂的AI系统(如工作流引擎、对话Agent、技能库)的部署运维复杂度大幅降低,使得开

weixin_27028523的博客 639

机器学习实战26-一种基于LightGBM的股市涨跌预测系统与代码实现过程

在全球经济一体化的背景下,股市作为经济活动的晴雨表,其波动与预测对于投资者、金融机构乃至国家政策制定者而言至关重要。随着金融市场的日益复杂化与信息量的爆炸式增长,股市分析不再仅限于基本面和技术面的传统研究,而是迫切需要更加精准、高效及智能化的方法来捕捉市场动态,以辅助决策制定。模型评估是确保LightGBM股市预测系统准确性和稳定性不可或缺的一环。通过综合运用多种评估指标、科学的验证方法以及深入的性能分析,我们不仅能够全面理解模型的能力和限制,还能为持续优化模型、提升预测准确性奠定坚实基础。

微学AI的博客 2329

Leetcode 2 Add Two Numbers

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 t...

博学 笃志 切问 近思 197

国产SerDes芯片(4)—纳芯微 NLS9116+NLS9246

本系列文章主要讲解国产SerDes芯片—纳芯微 NLS9116+NLS9246的相关知识。

零零刷的博客 823

leetcode 21. Merge Two Sorted Lists和2. Add Two Numbers

【代码】leetcode 21. Merge Two Sorted Lists和2. Add Two Numbers。

weixin_41554427的博客 443

SAP 实施:Waterfall vs. Agile —— 一场“结构性矛盾“的深刻比较先说结论:在 SAP 世界里,这从来不是“谁更好“的宗教问题,而是“你的项目 DNA 是什么“的战略选择。​

SAP 实施:Waterfall vs. Agile —— 一场"结构性矛盾"的深刻比较 先说结论:在 SAP 世界里,这从来不是"谁更好"的宗教问题,而是"你的项目 DNA 是什么"的战略选择。​ SAP 早已用 SAP Activate​ 给出了官方态度——它不是纯 Agile,也不是回头去搞旧 Waterfall,而是一个带质量门的混合架构。 1. 先回到本质:两者解决的是不同维度的风险 维度 Waterfall(传统 ASAP 路线)​ Agile(SCRUM/Kanban 式迭代)​

金牌架构师 338

〖Python网络爬虫实战㊴〗- 极验滑块介绍(一)

我们对这个看到不陌生,现在,大多数平台都是用的是这个平台的验证码,我们今天来学习一下,极验滑块验证码的逆向,其他的都差不多。我们了解到这个平台提供了许多验证的方式。现在大多数还是滑块比较多,滑块验证码是一种常见的验证方式,其主要思路为用户通过拖动滑块来完成验证。具体流程如下:首先,用户需要进行滑块验证码的操作,网站会向用户展示一张图片,图片上通常会有一些随机的文字和背景干扰。用户需要通过鼠标拖动滑块,将其移动到指定位置上,通常是将滑块拖动到图片的相应位置上来完成验证。

爱吃饼干的小白鼠的博客 2882

LeetCode-2. Add Two Numbers

刚刚我经历了可能是2017年3月22号的最大的大起大落。

public Blog myBlog(){ 1127

AI Agent的数据安全与隐私保护措施

AI Agent(人工智能代理)作为一种能够感知环境、做出决策并采取行动的智能实体,在现代社会的各个领域中得到了广泛的应用,如智能客服、自动驾驶、金融风险评估等。随着其应用的不断拓展,AI Agent处理和存储的数据量急剧增加,这些数据包含了大量的个人敏感信息和商业机密。因此,确保AI Agent的数据安全与隐私保护变得至关重要。本文的目的在于全面探讨AI Agent的数据安全与隐私保护措施,涵盖从数据的采集、存储、处理到传输的整个生命周期。

AGI×大数据,开启智能时代的认知跃迁;解码AGI,赋能数据驱动的智能革命。 2871

[leetcode] 2. 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

TstsUgeg的博客 407

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

[LeetCode] 2. Add Two Numbers

2. Add Two Numbers 反序求和 链表操作

ZY的博客 302

深度学习工具包 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")

Leetcode[2] Add Two Numbers and Leetcode[445] Add Two Numbers II

Leetcode[2] Add Two Numbers class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ...

只为分享 252

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Leetcode学习笔记:#2 Add Two Numbers

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. ...

ccystewart的博客 167

【LeetCode】2. Add Two Numbers 解题报告(Python)

【LeetCode】2. Add Two Numbers 解题报告(Python)题目描述解法一:先求和,再构建链表解法二:采用一个进位carry方便的完成一次遍历得出结果解法三:递归 题目地址:https://leetcode.com/problems/add-two-numbers/ 题目描述 You are given two non-empty linked lists represent...

ttinch的博客 261

2 Add Two Numbers(两数相加)

LeetCode题库Add Two Numbers(两数相加)解答

iMotherBoard的博客 412

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

2.Add Two Numbers

题目描述:中等难度 You are given two non-empyt 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...

猫敷雪 239
上一篇: 3Sum
下一篇: 63. Unique Paths II[dp]
FreeeLinux
博客等级 码龄11年 421粉丝 356原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值