Leetcode-8: String to Integer

Redmi Book Pro 15 2022 SSD更换实战指南 NVMe固态硬盘是现代笔记本存储系统的核心组件,其性能受PCIe通道分配、散热设计与BIOS兼容性多重制约。在轻薄本中,板载SSD焊死、无扩展插槽已成为典型设计瓶颈,导致容量不足、高温降频与带宽压缩等问题频发。更换第三方NVMe SSD需兼顾主控兼容性(如群联PS5013)、闪存同源性及导热结构匹配,尤其关注BIOS SATA模式(AHCI/RST切换)、屏蔽罩应力安装与0.15mm导热垫精度等工程细节。该操作适用于追求存储性能重构与长期稳定性的进阶用户,本质是面向硬件底层的系统级优化实践。 阅读详情
  1. String to Integer (atoi)
    Medium
    3.7K
    11.3K
    Companies
    Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).

The algorithm for myAtoi(string s) is as follows:

Read in and ignore any leading whitespace.
Check if the next character (if not already at the end of the string) is ‘-’ or ‘+’. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
Convert these digits into an integer (i.e. “123” -> 123, “0032” -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
Return the integer as the final result.
Note:

Only the space character ’ ’ is considered a whitespace character.
Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Example 1:

Input: s = “42”
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: “42” (no characters read because there is no leading whitespace)
^
Step 2: “42” (no characters read because there is neither a ‘-’ nor ‘+’)
^
Step 3: “42” (“42” is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.
Example 2:

Input: s = " -42"
Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
^
Step 2: " -42" (‘-’ is read, so the result should be negative)
^
Step 3: " -42" (“42” is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.
Example 3:

Input: s = “4193 with words”
Output: 4193
Explanation:
Step 1: “4193 with words” (no characters read because there is no leading whitespace)
^
Step 2: “4193 with words” (no characters read because there is neither a ‘-’ nor ‘+’)
^
Step 3: “4193 with words” (“4193” is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.

Constraints:

0 <= s.length <= 200
s consists of English letters (lower-case and upper-case), digits (0-9), ’ ', ‘+’, ‘-’, and ‘.’.

这道题的题目出的比较含糊,测试例子里面的情况都要特别注意。我的code写的太冗余,注释掉的code是Leetcode里面的,写的比较好。

#include <iostream>
#include <string>
#include <climits>

using namespace std;

int myAtoi(string str) {
    if (str.size()==0) return 0;   //empty string returns 0

    size_t flagPos=str.size();
    size_t startPos=str.size();
    for (auto i=0; i<str.size(); ++i) {
        if ((str.at(i)=='+' || str.at(i)=='-') && flagPos==str.size() )flagPos=i;

        if (isdigit(str.at(i))) {
            startPos=i;
            break;
        }
    }
    if (flagPos!=str.size() && (startPos-flagPos>1)) return 0;
    if (startPos==str.size()) return 0;   //invalid string returns 0
    else if (startPos>=1 && str.at(startPos-1)!='+' && str.at(startPos-1)!='-' && str.at(startPos-1)!=' ') return 0;

    bool positive=true;
    if ((startPos>0) && (str.at(startPos-1)=='-')) positive=false;
    if (positive && startPos>=2 && str.at(startPos-2)=='-') return 0;
    if (!positive && startPos>=2 && str.at(startPos-2)=='+') return 0;

    int result=positive? str.at(startPos)-'0' : '0' - str.at(startPos);
    for (auto i=startPos+1; i<str.size(); ++i) {
         if (isdigit(str.at(i))) {
            if (!positive) {
                if (result < INT_MIN / 10 || (result == INT_MIN / 10 && str.at(i) - '0' > 7))
                    return INT_MIN;
                else
                    result=result*10+'0'-str.at(i);
            }
            else {
                if (result >  INT_MAX / 10 || (result == INT_MAX / 10 && str.at(i) - '0' > 7))
                    return INT_MAX;
                else
                    result=result*10+str.at(i)-'0';
            }
         }
         else
            break;
    }

    return result;
}
#if 0
int myAtoi(string str) {
    int sign = 1, base = 0, i = 0;
    while (str[i] == ' ') { i++; }
    if (str[i] == '-' || str[i] == '+') {
        sign = 1 - 2 * (str[i++] == '-');
    }
    while (str[i] >= '0' && str[i] <= '9') {
        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
            if (sign == 1) return INT_MAX;
            else return INT_MIN;
        }
        base  = 10 * base + (str[i++] - '0');
    }
    return base * sign;
}
#endif // 0

int main()
{
    string s="123";
    cout<<myAtoi(s)<<endl;

    string s1="-23211";
    cout<<myAtoi(s1)<<endl;

    string s2="2147483647";
    cout<<myAtoi(s2)<<endl;

    string s3="-2147483648";
    cout<<myAtoi(s3)<<endl;

    string s4="000";
    cout<<myAtoi(s4)<<endl;

    string s5="+-2";
    cout<<myAtoi(s5)<<endl;

    string s6=" ++1""  -0012a42";
    cout<<myAtoi(s6)<<endl;

    string s7="2147483648";
    cout<<myAtoi(s7)<<endl;

    string s8="-2147483649";
    cout<<myAtoi(s8)<<endl;

    string s9="  +  413";
    cout<<myAtoi(s9)<<endl;

    string s10=" ++1";
    cout<<myAtoi(s10)<<endl;

    string s11=" b11228552307";
    cout<<myAtoi(s11)<<endl;

    string s12="    010";
    cout<<myAtoi(s12)<<endl;

    string s13="w10734368512";
    cout<<myAtoi(s13)<<endl;

    return 0;
}

二刷:

class Solution {
public:
    int myAtoi(string s) {
        long long res = 0;
        int len = s.size();
        int startPos = 0, endPos = 0;
#define UPP (long long)(pow(2, 31) - 1)
#define LPP (long long)(-pow(2, 31))
        while (startPos < len && s[startPos] == ' ') startPos++;
        if (startPos < len && 
            !isdigit(s[startPos]) && 
            s[startPos] != '+' && 
            s[startPos] != '-') return 0;
        if (s[startPos] == '+' || s[startPos] == '-') endPos = startPos + 1;
        else endPos = startPos;

        while (endPos < len && isdigit(s[endPos])) endPos++;
        string newS = s.substr(startPos, endPos - startPos);
        bool isNeg = (newS[0] == '-');
        if (newS[0] == '+' || newS[0] == '-') newS = newS.substr(1);
        int newLen = newS.size();
        for (int i = 0; i < newLen; i++) {
            res = res * 10 + (newS[i] - '0');
            if (res > UPP) return isNeg ? LPP : UPP;
        }
        return isNeg ? -res : res;
    }
};
Kettle Web版部署指南 看到以上的日志则表示启动成功。 阅读详情

相关推荐

TMS320F280049C 学习笔记11 控制率加速器 CLA 例程

总结了TI官方在C2000Ware_3_01_00_00版本中提供的7个与CLA相关的例程。

whyorwhnt的专栏 1万+

【LeetCode】字符串转换整数 (atoi) [M](模拟)

LeetCode 8:请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。采用模拟求解。

小七的博客 959

在MacBook M1/M2上,手把手教你打包包含嵌入模型的RagFlow Docker镜像(避坑指南)

本文详细指导如何在MacBook M1/M2上构建ARM64架构的RagFlow Docker镜像,涵盖环境准备、依赖处理、镜像构建及性能优化全流程。特别针对Apple Silicon芯片的兼容性问题提供解决方案,帮助开发者高效完成本地开发环境搭建。

weixin_26908317的博客 246

LeetCode(8)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 do not see below and ask yourself what are the possible

指尖飞舞 4704

SAP-MM-PR分配货源并转PO

SAP-MM-PR分配货源并转PO

yanzibing99的博客 5480

51、CAN总线干扰源分类与机理分析:共模与差模干扰

本文深入分析了CAN总线干扰问题,重点探讨了共模与差模干扰的机理及解决方案。作者通过实际案例指出,共模干扰主要来自地电位差、空间耦合和电源噪声,而差模干扰则源于信号反射、串扰和地环路。文章提出了现场诊断的"三板斧"方法:检测共模电压、差分信号质量和眼图分析,并给出了六条实用建议,包括接地设计、分支线处理、终端电阻布置等。最后通过AGV小车故障案例说明,许多CAN总线问题往往源于接地不良等细节问题,理解干扰机理才能有效解决问题。

2401_88858637的博客 72

LeetCode: Atoi

假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231, 231 − 1]。如果数值超过这个范围,qing返回 INT_MAX (231 − 1) 或 INT_MIN (−231) 。 示例 1: 输入: “42” 输出: 42 示例 2: 输入: " -42" 输出: -42 解释: 第一个非空白字符为 ‘-’, 它是一个负号。 我们尽可能将负号与后面所有连续出...

La745739773的博客 373

VHDL六层电梯控制器及仿真

六层电梯电梯 设计要求:设计一个六层电梯控制系统要求有超载、关门中断、提前关门清除报警信电梯外人的上升请求信号,电梯外人的下降请求信号, 电梯外人上升请求信号显示电梯外人下降请求信号显示到达楼层信号 设计思路:输入有clk时钟信号(频率为2Hz) full,deng,quick,clr超载、关门中断、提前关门清除报警c_u1,c_u2,c_u3,c_u4,c_u5电梯外人的上升请求c_d2,c_d3,c_d4,c_d5,c_d6 电梯外人的下降请求 d1,d2,d3,d4,d5,d6电梯内人的...

QQ_778132974的博客 1714

【LeetCode】String to Integer (atoi) 解题报告

这道题在LeetCode OJ上难道属于Easy,但是通过率却比较低,究其原因是需要考虑的情况比较低,很少有人一遍过吧。 【题目】 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge,

跳出温水的青蛙 1万+

RK3568平台开发系列讲解(音频篇)配置声卡

📢本篇文章介绍如何配置声卡。

内核笔记 2456

基于Simulink的光伏+储能家庭能源管理系统仿真

本文通过Simulink建模,分析了家庭光伏+储能系统的优化调度问题。针对光伏发电与用电高峰不匹配导致电费节省有限的问题,构建了包含5kW光伏、10kWh电池和6kW负荷的完整模型,设计了无控、规则控制和24小时经济优化三种策略。仿真结果显示,经济优化策略可使日电费降低32%,光伏自用率从45%提升至89%,尤其在晚高峰时段能显著减少高价购电。文章详细介绍了物理层建模、分时电价实现和控制策略设计方法,并探讨了天气预测、V2H等高级扩展功能,为家庭能源智能管理提供了实用解决方案。

xiaoheshang_123的博客 191

Leetcode:字符串转整数(atoi)

实现 atoi,将字符串转为整数。提示:仔细考虑所有输入情况。如果你想挑战自己,请不要看下面并自己考虑所有可能的输入情况。说明:这题解释的比较模糊(即没有指定输入格式)。你得事先汇集所有的输入情况。 atoi的要求:这个函数需要丢弃之前的空白字符,直到找到第一个非空白字符。之后从这个字符开始,选取一个可选的正号或负号后面跟随尽可能多的数字,并将其解释为数字的值。字符串可以在形成整数的字符后包括多余...

qitong111的专栏 1875

PD3.0详解 电源规则,全解!!!全解!!!

电源规则 大师匈今天谈一下PD3.0的电源规则,PD3.0标准标定的规则。 USB协议声称,为了世界和平世界环境,让大家用上统一标准的充电器,不用再为每一个用电设备都配一个专门的充电器,这些充电器各种各样的都有,所以有时候大师匈也很烦!!!那么为了维护世界和平,USB协议呢就制订了这个PD快充协议,还有它的规则,只要全世界都用PD,就解决了这个大问题。 在这里先了解一个关键字,PDP: Power Delivery Power PD电源的功率。 每个PD充电产品的功率要以0.5W的精度上报,比如大师匈做的P

大师匈的博客 1万+

LeetCode8:String to Integer

https://leetcode.com/problems/string-to-integer-atoi/ 问题描述 Implement atoi whichconverts a string to an integer. The function first discards as many whitespace characters as necessary until the fir...

一面之媛 117

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

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

qq_43271202的博客 199

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

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

LeetCode题目: 8. String to Integer (atoi) 原题链接:https://leetcode.com/problems/string-to-integer-atoi/description/ 解题思路:(以下来自百度)原型: int atoi(const char *nptr); 函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则

MyCodecOdecoDecodE的博客 532

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

LeetCode 8:《String to Integer (atoi) 》

编程思路:首先清除首尾空格,然后巧妙使用异常except,当字符不能转换成整数时,则进入except,Python实现代码如下: class Solution: # @return an integer def atoi(self, str): # 首先清除首尾空格 str = str.strip() # 如果是空

事了拂衣去,深藏功与名 884

LeetCode 8: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 do not see below and ask yourself what are the possible input case

哈哈的个人专栏 2258

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的博客 206

Leetcode 8:String to Integer (atoi)

Description:   请你来实现一个 atoi 函数,使其能将字符串转换成整数。   首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。   当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。   该字符串除了有效的整数部分之...

wayne17的博客 199

LeetCode 第8题:String to Integer

1:输入若为'    '时,该如何输出, 2:输入为'  010'时应该如何处理; 3:输入数字字符串前有'+'或'-';如何输出; 4:输入超出了int的最大最小值如何输出; 5:(最基本的问题)如何将字符转成数字(最简单*p-'0';即可) 以下是我调试时候的主函数 int main() { char str[] = "-2147483649";//输出为 -2

xx_xlz_solution的博客 331

LeetCode : No8 String to INteger (atoi)

题目链接: https://leetcode.com/problems/string-to-integer-atoi/ Implement atoi to convert a string to an integer. 解题的很简单想法: 讲所给字符串转换为int()可识别的字符串。 然后改进了以下两种情况: '  -0012a42'  >>>  -12 '+1'  

CoderPlay 345

leetcode[8]:String to Integer (atoi)

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 do not see below and ask yourself what are t

hahubaba的博客 592

LeetCode算法题之8:String to Integer (atoi)

LeetCode之9:String to Integer (atoi) 问题描述: 将字符串转换为合法的数字。题目地址 问题的陷阱与难点: 思路很好想,但是鲁棒性,鲁棒性,鲁棒性!!! 缺陷代码(99.50%) public int myAtoi(String str) { if (str == null || str.length() ==0) { return 0; ...

veatheroe的博客 191

Leetcode: 8.String to Integer atoi() 整数反转

8.String to Integer atoi() 整数反转 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 该字符...

Coding 404

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

旺仔馒头 308
上一篇: Leetcode-48: Rotate Image
下一篇: Leetcode-16: 3Sum Closest
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址