博客
关于我
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/

    你可能感兴趣的文章
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>