LeetCode题目: 8. String to Integer (atoi)

QT应用编程: 基于UDP协议设计的大文件传输软件 一、环境介绍 QT版本: 5.12.6 编译器: MinGW 32 传输协议: UDP 功能介绍:软件由客户端和服务器组成,客户端通过 UDP协议不断循环地向服务端发送文件,文件传输速率可以达到10MB/s以上,文件传输后支持自动删除,客户端上可以支持每分钟创建一个文件并以时间戳命名,每个生成的文件可以设置大小,默认大小为6GB; 服务端收到文件之后,将文件进行存储到本地,可以指定时间自动删除文件;服务端可以动态计算传输速率,并写入日志文件; 服务器可以支持同时接收多个客户端的文件上传。... 阅读详情

LeetCode题目: 8. String to Integer (atoi)

原题链接:https://leetcode.com/problems/string-to-integer-atoi/description/

解题思路:

(以下来自百度)

原型: int atoi(const char *nptr);
函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。

照着上面实现即可。

核心思想:

1.先寻找到第一个非空格位置

2.判断是否有正负号,并记录正负

3.进行数字相加,每有一个新数字,sum=sum*10+newNumber。

4.给结果重新加上正负号

代码细节:

1.如果越界,返回界内最接近该值的值,例如:-2147483649—>-2147483648,2147483649—>2147483647

2.如果第一个非空格字符不是数字或正负号,或遍历到结尾,直接返回0。

3.为了判断是否越界,用longlong储存结果。(long不够长)


坑点:

1.从第一个非空格字符开始

2.无法越界,取值范围有限制

3.可以识别”+123”之类的正数


代码:

int myAtoi(string str) {
    bool isNegative = false;     // 表示正负
    long long output = 0;     // 表示输出值 

    // 如果输入为空
    if (str.empty())  return output;

    // 寻找第一个空格后字符位置 
    int i;
    for (i = 0; i < str.length(); i++)
        if (str[i] != ' ')  break;

    // 没有找到,返回0
    if (i == str.length())  return output;
    else if (str[i] == '+' || str[i] == '-') {
        if (str[i] == '-')  isNegative = true;
        i++;
    } 
    else if (!isdigit(str[i]))  return output;

    // 进行字符相加
    while (i < str.length() && isdigit(str[i])) {
        output *= 10;
        output += str[i] - '0';
        i++;

        // 判断是否越界 
        if (output > 2147483648) {
            output = 2147483648;
            break;
        }
    }

    // 添加正负号,int取值范围为-2^32----2^32-1 
    if (!isNegative) {
        if (output == 2147483648)  output--;
    }
    else  output = -output;

    return (int)output;
}
基于PyQt5和OpenCV的传统图像分割应用UI程序 主要功能包括:加载和显示图像应用多种图像分割算法调整算法参数保存处理结果。 阅读详情

相关推荐

蛋白质组学进阶指南 | (八)差异蛋白筛选与功能解析实战

本文是蛋白质组学差异蛋白筛选与功能解析的实战指南。详细讲解了如何利用R语言的limma包进行差异表达分析,结合FDR校正和差异倍数设定筛选关键蛋白,并通过火山图可视化结果。进一步介绍了使用clusterProfiler进行GO与KEGG功能富集分析,以及利用STRING数据库和Cytoscape构建蛋白互作网络以识别枢纽分子,最终串联分析形成可验证的生物学假说。

weixin_29208077的博客 740

leetcode题目-8.String to Integer (atoi)

题目介绍:Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting fro...

zydapangzi的博客 151

unet学习笔记(milesial/Pytorch-UNet)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 unet学习笔记(milesial/Pytorch-UNet)原理讲解unet_parts.py内容predict.py内容 所用到的代码Pytorch-UNet/predict.py at master · milesial/Pytorch-UNet ·GitHub 原理讲解 蓝/白色框表示 feature map; 蓝色箭头表示 3x3 卷积,用于特征提取; 灰色箭头表示skip-connection,用于特征融合; 红色箭头.

weixin_67138138的博客 2553

3.leetcode题目8:String to Integer (atoi)

这道题目理解起来有点费劲,反正我理解了很久都没懂。。。 题目要求:将字符串转换为整数输出 1.空字符串时返回0; 2.丢弃前面的空白字符直到第一个非空白字符; 3.判断第一个字符是否为“+”或“-”,记录(也有可能第一个字符就是数字); 4.对后面的字符进行判断,若为数字则记录,否则,终止转换; 5.考虑转换后的结果是否溢出,溢出则输出相应符号的边界值。 过程中遇到了很多错误

hzj的博客 420

pe卸载win10更新补丁_禁用Win10系统更新

众所周知,最近WIN10的强制更新导致了很多问题。如:(部分专业软件系统更新后无法使用,硬件中键盘、鼠标、指纹之类的硬件,更新补丁后失灵等问题)。而之前的禁用WindowsUpdate的方法已经失效。下面我们另辟蹊径,利用系统权限的方法使Win10无法更新,达到禁用更新的目的。1.计算机管理-服务中禁用Windows Update服务。2.打开C:\Windows\softwareDistribu...

weixin_39702479的博客 1万+

从静态到动态:如何用Deformable 3DGS和4DGS实现高效动态场景建模

本文深入探讨了Deformable 3DGS和4DGS在动态场景建模中的技术突破,详细解析了这两种方法如何高效处理动态内容。Deformable 3DGS通过引入时间维度的变形场扩展传统3DGS,而4DGS则采用四维时空体素分解方法,两者均显著提升了动态场景建模的效率和质量,适用于虚拟现实、增强现实等应用场景。

weixin_29063035的博客 433

LeetCode 8. String to Integer (atoi) 字符串转整形

LeetCode 8. String to Integer (atoi) 字符串转整形 8. String to Integer (atoi) Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary unt...

goasleep的博客 216

解决rt-thread上使用SPI+DMA

首先阐述下遇到的问题 使用SPI读取icm20602数据,读取频率为1000hz,使用stm32f407主控,发现CPU占用率达到了70%,将此线程注释掉后CPU占用率掉到25%,看来这里要着重优化,便萌生了使用DMA的想法。 使用SPI+DMA要进行的配置 1.开启RTT设备驱动。点击自己的工程 ->RT-Thread Setting2.在board.hzhong3.在board.c文件里加入以下函数,此函数受设备框架调用 void HAL_SPI_MspInit(SPI_HandleTypeDef

响望的博客 8085

LeetCode #8 String to Integer (atoi)

LeetCode #8 String to Integer (atoi) Question Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ...

weixin_30414305的博客 115

IEC 61400-1:2019 附录 C 湍流模型全面解读

IEC 61400-1:2019 附录 C 全面解读

weixin_46713695的博客 471

高效与灵活相结合:Verilog编写的跨时钟域循环缓冲控制器解析

循环缓冲区,也被称作循环队列、环形缓冲区,是一种数据结构,其主要特性是使用一个固定大小的缓冲区作为数据的存储空间,这个缓冲区在逻辑上被视作是首尾相接的。虽然Verilog是一种常用的硬件描述语言,被广泛应用在FPGA和ASIC设计中,但是在描述循环缓冲区时,它并没有提供一种直接且灵活的方式来指定循环缓冲区的参数,如字长、缓冲区深度、缓冲区数量等。这给硬件设计带来了一定的不便。同时,该控制器的设计也充分考虑了硬件资源的利用率,通过优化的算法和数据结构,使得在实现高性能的同时,也能够有效地节省硬件资源。

qq_38334677的博客 1221

题目地址(8. 字符串转换整数 (atoi))

题目地址(8. 字符串转换整数 (atoi)) https://leetcode.cn/problems/string-to-integer-atoi/ 题目描述 请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。 函数 myAtoi(string s) 的算法如下: 读入字符串并丢弃无用的前导空格 检查下一个字符(假设还未到字符末尾)为正还是负号,读取该字符(如果有)。 确定最终

潜行前行的专栏 128

把 SNC 支持的通信链路一次讲透,SAP GUI、RFC、CPIC、SAProuter 到底谁在保护谁

摘要: SNC(Secure Network Communications)是SAP系统中用于保护特定通信链路的安全机制,主要应用于DIAG、RFC、CPIC等SAP协议,而非HTTP等互联网协议(后者由SSL/TLS处理)。其核心在于保护通信端点之间的逻辑链路,需在发起方和接收方同时配置SNC参数,包括SNC名称、保护等级(QoP)等。实际项目中,SNC的配置涉及多个层面,如SAP GUI到ABAP平台的登录链路、外部程序通过RFC/CPIC连接ABAP的认证、ABAP系统间的跨系统通信等。配置不当可能导

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 250

Leetcode-8. String to Integer (atoi)(字符串转整数)

Leetcode-8. String to Integer (atoi)Implement atoi which converts a string to an integer.The function first discards as many whitespace characters as necessary until the first non-whitespace character...

Alatebloomer的博客 334

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

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

【力扣Leetcode题解系列之0008—String to Integer (atoi):字符串转换整数 (atoi) 解题攻略】

本文介绍了力扣第8题“字符串转换整数(atoi)”的解题方法。题目要求实现一个类似C/C++中atoi的函数,将字符串转换为32位有符号整数。解题需处理以下关键点:去除前导空格、判断正负号、提取连续数字字符并进行边界检查。文章提供了Python正则表达式法和常规遍历法两种解法,并给出了Python、Java、C、C++四种语言的代码实现。正则表达式法简洁高效,而常规遍历法则更直观地展现了处理流程。两种方法都需要注意32位整数的溢出问题,当结果超出[-2^31, 2^31-1]范围时返回对应的边界值。

youngerwang的博客 895

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】8. String to Integer (atoi)(C++)

地址:https://leetcode.com/problems/string-to-integer-atoi/ 题目: Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the firs...

Ethan95的博客 595

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

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

Leetcode 8. String to Integer (atoi)

@[TOC](Leetcode 8. String to Integer (atoi)) 题目说明 Implement atoi which converts a string to an integer. 题目可以简短概括为将一个输入的字符串转化为数值型输出,其中特殊情况有: 1.首字符可以是空格/数字/正负符号(有效输入为多空格直至出现后面两种情况之一) 2.首字符一旦不是上述三种情况之一直...

babi_qq的博客 274

[LeetCode]String to Integer (atoi)

题目要求: mplement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible inpu

zhouworld16的专栏 5901

LeetCode 8 — String to Integer (atoi)(C++ Java Python)

题目:http://oj.leetcode.com/problems/string-to-integer-atoi/ Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please

龙之梦 4864

String to Integer (atoi) -- LeetCode

原题链接:http://oj.leetcode.com/problems/string-to-integer-atoi/  这道题还是对于Integer的处理,在Reverse Integer这道题中我有提到,这种题的考察重点并不在于问题本身,而是要注意corner case的处理,整数一般有两点,一个是正负符号问题,另一个是整数越界问题。思路比较简单,就是先去掉多余的空格字符,然后读符号(

Code Ganker 1万+

【LeetCode】8. String to Integer (atoi)(Python)

Problem 字符串转为整型 https://leetcode.com/problems/string-to-integer-atoi/ 实现atoi将字符串转换为整数。 该函数首先丢弃所需数量的空白字符,直到找到第一个非空白字符。然后,从该字符开始,采用可选的初始加号或减号,后跟尽可能多的数字,并将它们解释为数值。 字符串可以包含在形成整数之后的其他字符,这些字符将被忽略并且对此函数的行为没有...

E.W的博客 1692

LeetCode - String to Integer (atoi)

LeetCode - String to Integer (atoi)

杂的文 543

Leetcode1-50: 08, 8. String to Integer (atoi)

@[TOC](Leetcode1-50: 08, 8. String to Integer (atoi)) 问题描述 Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from t

Y123iwantit的博客 205

LeetCode--String to Integer (atoi)

String to Integer (atoi) 1 题目 Implementatoiwhichconverts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character i...

Vilin的博客 304

【Leetcode】String to Integer (atoi)

题目链接:https://leetcode.com/problems/string-to-integer-atoi/ 题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, plea

业精于勤,荒于嬉 1566

String to Integer atoi -- LeetCode

String to Integer atoi -- LeetCode

weixin_43418664的博客 293
上一篇: LeetCode题目: 7.Reverse Integer
下一篇: LeetCode题目:9.Palindrome Number
MyCodecOdecoDecodE
博客等级 码龄10年 66粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值