LeetCode-2:Add Two Numbers (列表做整数相加)

0欧电阻、电感、磁珠单点接地时有什么区别? 0欧电阻、电感、磁珠单点接地时有什么区别? #电阻,#电感,#磁珠 一、0欧姆电阻 重点介绍:模拟地和数字地单点接地。 只要是地,最终都要接到一起,然后入大地。如果不接在一起就是“浮地”,存在压差,容易积累电荷,造成静电。地是参考0电位,所有电压都是参考地得出的,地的标准要一致,故各种地应短接在一起。 人们认为大地能够吸收所有电荷,始终维持稳定,是最终的地参考点。虽然有些板子没有接大地,但发电厂是接大地的,板子上的电源最终还是会返回发电厂入地。如果把模拟地和数字地大面积直... 阅读详情

题目:

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.

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

问题解析:

给定两个链表分别代表两个非负整数。数位以倒序存储,并且每一个节点包含一位数字。将两个数字相加并以链表形式返回。

链接:

https://leetcode.com/problems/add-two-numbers/description/

思路标签:

数据结构:List

解答:

1. C++
/**
 * 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 preHead(0), *p = &preHead;
        int extra = 0;
        while(l1 || l2 || extra){
            int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
            extra = sum / 10;
            p->next = new ListNode(sum % 10);
            p = p->next;
            l1 = l1 ? l1->next : l1;
            l2 = l2 ? l2->next : l2;
        }

        return preHead.next;
    }
};
2. python
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        root = n = ListNode(0)
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            n.next = ListNode(val)
            n = n.next
        return root.next

C++相关:

List:http://blog.youkuaiyun.com/yas12345678/article/details/52601578

迟滞比较器原理及计算 为什么要用迟滞比较器 在讲迟滞比较器之前,我们先看一个案例。 在产品设计中常常需要用到电机,而电机在从运转到停止过程中需要泄放能量,这种能量大部分以电压的形式反馈回电源母线(Vbus)导致Vbus母线电压升高,特别是功率大又转速快的电机需要急刹时,产生的反馈电压更高,严重时可能导致母线上其他器件的损坏。 为了防止将电机反馈的能量泄放掉,我们需要设计一个电路来检测母线电压,当母线电压高于某一安全阈值时,打开MOSFET Q1将母线上的能量通过电阻R5以热的形式消耗掉。 假如用一般的比较器,设计如下: Vbu 阅读详情

相关推荐

ResNet与注意力机制:深度学习中的强强联合

本文详细介绍了ResNet和注意力机制的基本原理,并探讨了如何将两者结合,以提升网络的性能。通过在ResNet中引入注意力机制,网络可以自适应地调整特征图的重要性,从而更加关注于关键区域,提升模型的性能。实验结果表明,引入注意力机制后,ResNet的性能得到了显著提升。未来,随着注意力机制的不断发展,我们可以期待更多创新的网络架构和训练方法,进一步提升深度学习模型的性能。

2401_82355416的博客 1783

Python中两个列表数字“相加”的4种方法

Python中两个列表数字“相加”的4种方法

y1282037271的博客 4万+

告别视频广告:OpenWrt下luci-app-adbyby plus/lite的完整配置与避坑手册

本文详细介绍了在OpenWrt路由器上配置Adbyby Plus/Lite广告屏蔽工具的完整流程与优化方案。从环境准备、规则文件手动配置到高级性能调优,帮助用户有效拦截视频前贴片广告和弹窗广告,提升家庭网络浏览体验。特别针对官方源停止维护的问题,提供了实用的规则更新解决方案。

weixin_29306011的博客 742

【Python列表】Python列表内数值相加的方法

sum([1, 2, 3, 4]) # 结果为10 sum([1, 2, 3], 4) # 结果也为10

恒治学 1万+

基于奥比中光Orbbec Astra Pro与ROS实现实时3D环境建模:orb_slam2实战指南

本文提供了一份详细的实战指南,介绍如何使用奥比中光Orbbec Astra Pro深度摄像头与ROS系统,部署并运行ORB-SLAM2算法,实现实时3D环境建模与定位。内容涵盖从驱动安装、环境配置、算法编译到摄像头标定与性能调优的全流程,旨在帮助开发者快速搭建一套高性价比的视觉SLAM系统。

weixin_29054399的博客 336

ui(new Ui::MainWindow)的解析

Ui命名空间的变量名,和默认空间的变量名虽然一样,但实际是两个不同的东西。所以构造函数中调用MainWindow是没问题的,因为它不是在调用自身,而是在调用其他命名空间下的另一个同名的MainWindow类。这里使用C++的成员初始化列表语法,初始化成员变量指针ui,可这里有个问题,在MainWindow的构造函数中new 一个MainWindow,这又调用一下MainWindow的构造函数,这岂不是会死循环?ui_mainwindow.h文件。mainwindow.h文件.

sinat_31608641的博客 1193

List集合中整数相加

在使用List集合中我们避免不了其中整数相加的问题,在最开始我么必须根据下标进行一个一个相加 现在OR 我们有一个新的东西,这个东西它叫Stream流的东西能够非常方便非常快捷的帮助我们把整数或者BigDecimal类型数据相加起来 方法:集合的变量名 点 stream() 点 mapToint(这里面是集合中的泛型::intValue)点 sum() 这就可以了,我这边演示的是Intager整数类型的示范,下面整体代码奉上! public Result<Integer> g...

m0_50814496的博客 2053

SAP ABAP CO核心扩展-为企业定制ZCKM3N物料价格分析增强(CKM3 CKM3N CKM8N)

这篇文章,将为大家讲述物料价格分析扩展增强(ZCKM3N)的方法和原理,并基于CKM3N的视图之一“CV成本组件”,教大家如何一步步实现批量输出多工厂物料的物料价格分析报表。

SAP李斌,本人承诺所有原创文章均不使用任何AI生成技术,请大家放心阅读。 3985

python列表内数字怎么求和_python怎么把列表的值相加

2016-12-14 回答第一步:我分析如果从一堆数里随机抽取几个,并且按原来的顺序输出的话,那么至少要随机两次才能完成,第一次随机的值是确定随机几个数,第二次随机是确定随机的值。第二步:随机抽取几个可以用random.randint(1,n)这个函数来实现,这个n代表所要随机列表的长度。第三步:上一步出来一个数决定此次随机出几个值出来,现在假定是n,再次随机就是从列表里随机抽取n个值这个可以用r...

weixin_39981681的博客 1万+

CS 188 Project3(RL) Q10:Approximate Q-Learning

实现一个近似的Q-learning学习代理,它学习状态特征的权重,其中许多状态可能共享相同的特征。在qlearningAgents.py中的ApproximateQAgent类中编写实现,它是PacmanQAgent的子类。 注:近似Q-learning学习假设在状态和动作对上存在一个特征函数f(s,a),它产生一个向量f1(s,a) .. fi(s,a) .. fn(s,a)特征值。我们在fe...

大模型与Agent智能体 2657

高温环境下(100℃以上)相机的几种保障方案

高温环境下相机保障措施摘要:针对120℃以上高温环境,相机需采取多重防护:1.散热设计采用金属机身、散热鳍片或风扇;2.关键部件选用耐高温材料(铝合金、特种玻璃);3.电子元件需军规级芯片并做三防处理;4.建议外接电源或耐高温电池。工业相机(如FLIR A655sc、Basler ace)及特种机型(Ximea xiQ)具备高温适应性,普通相机可加装隔热套件配合冷却系统。选择时需关注传感器信噪比和全局快门性能,并设置温度监控保护机制。注意高温会加速设备老化,需定期检测维护。(149字)

start_up_go的博客 1588

两数之和:给定一个整数数组,找出其中两个数相加等于目标值

题目:给定一个整数数列,找出其中和为特定值的那两个数。 你可以假设每个输入都只会有一种答案,同样的元素不能被重用。 有三种思路: 第一个思路:遍历数组i从第一个数开始,j从(i+1)开始,直到找到合适的值。这个算法的时间复杂度为O(n2),空间复杂度为O(1)。 第二个思路:在前一个算法的基础上降低时间复杂度。我们可以将数组排序,然后定义两个指针,一个指针i从左向右,另一个从j...

疯狂的卡夫卡的博客 2万+

PCL 欧式聚类分割【2026最新版】

PCL中欧式聚类提取算法原理详解、代码实现以及一个大自然场景地物分割提取并保存分割结果到本地文件夹的应用案例。

点云侠的博客 40万+

LeetCode //C - 445. Add Two Numbers II

【代码】LeetCode //C - 445. Add Two Numbers II。

Made in Code 1897

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

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

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode第二题:两数相加(Add Two Numbers)

LeetCode第二题:两数相加 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 num...

三年研究生能改变多少 5220

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

2 Add Two Numbers(两数相加)

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

iMotherBoard的博客 411

LeetCode-2. Add Two Numbers

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

public Blog myBlog(){ 1125

【Leetcode】2. 两数相加(Add Two Numbers)

Leetcode - 2 Add Two Numbers (Medium) 题目描述:使用链表表示两个正整数,返回两正整数相加结果,使用链表表示。 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. public ListNode addT...

厉兵秣码 274

2. Add Two Numbers

2. Add Two Numbers Medium 59971568Share 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...

Joy 651

LeetCode-Add Two Numbers(JS题解)

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

爪蛙没有爪的博客 323

LeetCode 2. 两数相加(Add Two Numbers)

LeetCode.jpg 2. 两数相加 2. 两数相加 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输...

墨1024 499

2. Add Two Numbers 两数相加

题目:Add Two Numbers 两数相加 难度:中等 You are given twonon-emptylinked lists representing two non-negative integers. The digits are stored inreverse orderand each of their nodes contain a single digit. ...

qq_21963133的博客 225

ACM之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 re

Microstrong 657

Add Two Numbers

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

Yuke的博客 238

LeetCode2 两数相加 Add Two Numbers

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

沙码龙 225
上一篇: Kaggle_Titanic生存预测 -- 详细流程吐血梳理
下一篇: LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
大树先生的博客
博客等级 码龄9年 2692粉丝 200原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值