博客
关于我
Leetcode 8. 字符串转换整数 (atoi)
阅读量:243 次
发布时间:2019-03-01

本文共 1449 字,大约阅读时间需要 4 分钟。

为了实现一个能够将字符串转换为整数的 atoi 函数,我们需要处理字符串中的空格、符号和数字字符,并确保正确处理溢出情况。以下是实现步骤和优化后的代码:

实现步骤:

  • 处理空格:首先遍历字符串,跳过所有前面的空格,找到第一个非空格字符的位置。
  • 处理符号:如果第一个非空字符是 '+' 或 '-',记录符号并继续读取后面的数字字符。
  • 读取数字字符:从符号后面开始,读取所有连续的数字字符,直到遇到非数字字符为止。
  • 计算数值:将读取到的数字字符转换为整数值,并检查是否溢出32位有符号整数范围。
  • 处理溢出:如果数值溢出,返回相应的 INT_MAXINT_MIN
  • 返回结果:根据符号和数值计算结果返回整数值。
  • 优化后的代码:

    #include 
    #include
    using namespace std;int myAtoi(string str) { if (str.empty()) return 0; size_t i = 0; // 忽略前面的空格 while (i < str.size() && isspace(str[i])) { i++; } if (i >= str.size()) return 0; // 仅包含空格或空 int sign = 1; if (str[i] == '-') { sign = -1; i++; } else if (str[i] == '+') { i++; } else { // 第一个非空字符不是符号或数字,直接返回0 return 0; } long long num = 0; bool overflow = false; bool has_invalid = false; while (i < str.size() && isdigit(str[i])) { num = num * 10 + (str[i] - '0'); if (num > INT_MAX) { overflow = true; break; } if (num < INT_MIN) { overflow = true; break; } i++; } if (overflow) { return (sign == -1) ? INT_MIN : INT_MAX; } else { return (sign == -1) ? -num : num; }}

    代码解释:

    • 空格处理:使用 isspace 函数跳过前面的空格,找到第一个非空字符。
    • 符号处理:判断符号并记录符号值,继续处理后续字符。
    • 数字处理:读取连续的数字字符,计算数值。在读取过程中检查是否溢出,避免数值超过32位整数范围。
    • 溢出处理:如果数值溢出,返回 INT_MAXINT_MIN
    • 返回结果:根据符号和计算的数值返回最终结果。

    这个函数能够处理各种有效和无效输入情况,确保转换正确或返回默认值0。

    转载地址:http://qjev.baihongyu.com/

    你可能感兴趣的文章
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>