博客
关于我
12.把字符串转换成整数
阅读量:192 次
发布时间:2019-02-27

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

要解决这个问题,我们需要将一个字符串转换成整数,并确保该字符串是合法的数值表达。如果字符串不是合法的数值,或者数值为0,则返回0。

方法思路

  • 检查空字符串:如果输入字符串为空,直接返回0。
  • 处理正负号:检查字符串的第一个字符是否为'+'或'-',记录符号并将符号字符替换为'0',以便后续处理。
  • 遍历字符:逐个检查字符串中的每个字符是否为数字。如果发现非数字字符,返回0。
  • 计算数值:将字符串中的每个字符转换为对应的数字值,并累加得到总和。
  • 应用符号:根据记录的符号,调整数值的正负,返回最终结果。
  • 解决代码

    int StrToInt(string str) {    if (str.empty()) {        return 0;    }    int flag = 1;    if (str[0] == '-') {        flag = -1;        str[0] = '0';    } else if (str[0] == '+') {        str[0] = '0';    }    int sum = 0;    for (int i = 0; i < str.size(); ++i) {        if (str[i] < '0' || str[i] > '9') {            return 0;        }        sum = sum * 10 + (str[i] - '0');    }    return flag * sum;}

    代码解释

  • 空字符串检查:如果输入字符串为空,直接返回0。
  • 符号处理:检查字符串的第一个字符是否为'-'或'+',记录符号并将符号替换为'0',以避免后续处理中出现非数字字符。
  • 字符遍历:逐个检查每个字符是否为数字。如果发现非数字字符,返回0,表示字符串不合法。
  • 数值计算:将每个字符转换为对应的数字值,并累加得到总和。
  • 符号应用:根据记录的符号,调整数值的正负,最终返回结果。
  • 这个方法确保了我们能够正确且安全地将字符串转换为整数,同时处理了各种边界情况,如空字符串、非法字符和前导零等。

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

    你可能感兴趣的文章
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    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 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
    查看>>