【leetcode 题解】415. Add Strings【E】

leetcode java 本资源是leetcode经典50题,java版本,互联网面试必备! 立即下载

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Subscribe to see which companies asked this question


这个简直很直白,最后一行注释掉的是好用的python的整数类型

总感觉程序哪里写的有点儿丑~~~



class Solution(object):
    def addStrings(self, num1, num2):

        l1 = len(num1)
        l2 = len(num2)

        lmin = min(l1,l2)
        lmax = max(l1,l2)

        res = [0] * (lmax+1)
        #print res

        for i in xrange(1,lmin+1):
            res[-i] = int(num1[-i]) + int(num2[-i])
            #print i,res

        if l1 > l2:
            for i in xrange(lmin+1,lmax+1):
                res[-i] = int(num1[-i])
        else:
            for i in xrange(lmin+1,lmax+1):
                res[-i] = int(num2[-i])

        for i in xrange(1,lmax+1):
            if res[-i] > 9:
                res[-i] -= 10
                res[-i-1] += 1
        rres = ''

        for i in res:
            rres += str(i)
        if rres[0] == '0':
            rres = rres[1:]
        return rres


        #return str(int(num1) + int(num2))


Unity AR开发实战:从Vuforia图片识别到实体识别全流程解析 增强现实(AR)技术通过计算机视觉算法将虚拟信息叠加到现实世界,其核心原理在于对现实环境的感知与理解。在移动端AR开发中,图像识别与物体识别是实现虚实融合的关键技术,它们决定了虚拟内容能否准确、稳定地与现实对象对齐。Vuforia作为成熟的商业AR SDK,为开发者提供了从平面图像识别(Image Target)到三维实体识别(Model Target)的完整解决方案,极大降低了计算机视觉技术的应用门槛。在工程实践中,Vuforia通过封装复杂的特征提取与匹配算法,使开发者能够专注于交互设计与内容制作,广泛 阅读详情

相关推荐

新手避坑指南:用COMSOL Multiphysics仿真气体放电(汤逊vs.流注)

本文详细介绍了使用COMSOL Multiphysics仿真气体放电的实战指南,涵盖汤逊理论和流注模型的实现方法。通过对比两种放电模型的关键参数和物理场配置,帮助新手避免常见错误,准确预测气体击穿过程。文章还提供了工程应用案例,如高压绝缘子设计优化,展示了仿真技术在电力设备绝缘设计中的实际价值。

weixin_28716181的博客 473

LeetCode-字符串相加-简单

字符串相加

wxy 973

PT32F030与MT6826S SPI通讯实战:从硬件连接到数据交互全流程解析

本文详细解析了PT32F030与MT6826S通过SPI通讯的全流程,包括硬件连接、电路设计、SPI外设初始化配置以及数据交互协议实现。通过实战案例和代码示例,帮助开发者快速掌握PT32F030与MT6826S的SPI通讯技术,实现精准的角度和速度数据采集。

weixin_29189373的博客 420

力扣(leetcode)第415题字符串相加(Python)

你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。输入:num1 = “11”, num2 = “123”输入:num1 = “456”, num2 = “77”输入:num1 = “0”, num2 = “0”num1 和num2 都只包含数字 0-9。num1 和num2 都不包含任何前导零。

qq_58737789的博客 678

告别BAPI!深入SAP S/4HANA BP框架:cl_md_bp_maintain维护客户主数据的正确姿势与性能优化

本文深入解析SAP S/4HANA中cl_md_bp_maintain框架的高效实践与架构设计,对比传统BAPI方式,展示其在业务伙伴(BP)主数据维护中的性能优势与现代化特性。通过详细代码示例和性能测试数据,揭示如何利用该框架实现批量处理、集中校验及智能错误恢复,助力企业从ECC向S/4HANA平滑迁移。

weixin_30596735的博客 358

hi3516cv610在PQStream上实现拉出图像,windows和板端操作记录

PQStream拉出图像

weixin_51838255的博客 728

LeetCode-Python-415. 字符串相加

给定两个字符串形式的非负整数num1和num2,计算它们的和。 注意: num1和num2的长度都小于 5100. num1和num2都只包含数字0-9. num1和num2都不包含任何前导零。 你不能使用任何內建 BigInteger 库,也不能直接将输入的字符串转换为整数形式。 思路: 先排除corner case, 然后调整一下nums1,nums2的相对...

Keep Coding 983

基于YOLOv11的水果/商品/食堂/蔬菜/饮料/书籍识别与计价系统,前台+后台管理系统

基于YOLOv11的水果/商品/食堂/蔬菜/饮料/书籍识别与计价系统,前台+后台管理系统

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 1220

[leetcode] 415. Add Strings @ python

原题 Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is &lt; 5100. Both num1 and num2 contains only digits 0-...

闲庭信步 344

QGis软件 —— 2、QGis加载在线地图两种方式(谷歌地图、天地图)

QGis软件 —— 2、QGis加载在线地图两种方式(谷歌地图)

1万+

基于YOLO的智能视频监控异常行为检测研究:从算法原理到落地部署的全栈实践

本文深入探讨如何利用 YOLO(You Only Look Once)系列算法构建一套端到端的异常行为检测系统。文章首先回顾 YOLOv8 在时空建模上的局限,然后提出“YOLO-STA(Spatio-Temporal Aggregation)”轻量级改进框架,在公开数据集 UCF-Crime 上将异常行为检测的 mAP@0.5 从 72.4 提升到 80.1;接着给出完整训练、推理、部署的 Python 代码(PyTorch + TensorRT),并介绍如何仅用 4 GB 显存的 Jetson Xavi

博客 1331

[leetcode: Python]415. Add Strings

Title Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9

cyy2learn的博客 1376

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Leetcode 415.字符串相加(Add Strings)

Leetcode 415.字符串相加 1 题目描述(Leetcode题目链接)   给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 注意: num1 和num2 的长度都小于 5100. num1 和num2 都只包含数字 0-9. num1 和num2 都不包含任何前导零。 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。 2 题解   按位相加,记录进位。 class Solution: def addStrings(self,

qq_39378221的博客 246

数学建模模型总结

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

深度学习工具包 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 415. Add Strings (python+cpp)

Leetcode 415. Add Strings题目解法1:补0加逆向for循环解法2:逆向while循环 题目 解法1:补0加逆向for循环 class Solution: def addStrings(self, num1: str, num2: str) -> str: m = len(num1) n = len(num2) if m>n: num2 = '0'*(m-n)+num2 els

qq_37821701的博客 157

OV9734 DATASHEET,完整规格书

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

【LeetCode】415. Add Strings 字符串/大整数相加 - Easy

[LeetCode] 415. Add Strings 字符串相加 Given two non-negative numbersnum1andnum2represented as string, return the sum ofnum1andnum2. Note: The length of bothnum1andnum2is < 5100. Both...

It’s All Uphill From Here 288

LeetCode 415. Add Strings题解 字符串加和

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

ZXC的专栏 813

LeetCode - 415 - 字符串相加(add-strings)

Create by jsliang on 2019-07-25 17:24:282019-07-25 19:08:40一 目录不折腾的前端,和咸鱼有什么区别| 目录 | ...

weixin_41806099的博客 256

【LeetCode】415 Add Strings (java实现)

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34270865的博客 105

[LeetCode] 415. Add Strings_Easy tag: String

Given two non-negative integersnum1andnum2represented as string, return the sum ofnum1andnum2. Note: The length of bothnum1andnum2is < 5100. Bothnum1andnum2contains only digits...

weixin_30402085的博客 110

[LeetCode 415] Add Strings(Python)

题目描述 Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: 1.The length of both num1 and num2 is < 5100. 2.Both num1 and num2 contains

yurenguowang的博客 780

[LeetCode]415. Add Strings(计算两个字符串表示的数字的和)

415. Add Strings原题链接 Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 给定两个用字符串表示的非负整数num1和num2,返回用字符串表示的num1和num2的和。Note: The length of both num1

whl_program的博客 2994

leetcode415.python字符串相加

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。注意:num1 和num2 的长度都小于 5100.num1 和num2 都只包含数字 0-9.num1 和num2 都不包含任何前导零。你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。第一种class Solution(object): def addStrings(self, n...

IT_job的博客 1969

LeetCode 415. Add Strings 题解(C++)

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

prayyojay的博客 1806

LeetCode 415. Add Strings(字符串相加)python3版本

代码转载自:点击这里可以查看 我给加了很详细的注解,这样看起来就方便多了,尤其是像我一样的新手 class Solution(object): def addStrings(self, num1, num2): &quot;&quot;&quot; :type num1: str :type num2: str :rtype: str &quot;&quot;...

qq_37002901的博客 443
上一篇: 【leetcode】404. Sum of Left Leaves【E】
下一篇: 【leetcode】409. Longest Palindrome【E】
Vicky_Vicky_990121
博客等级 码龄14年 23粉丝 187原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值