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 the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Difficulty:Medium

TIME:18MIN

解法

这道题的的意思是说把字符串转换为int类型的数字,转换的过程要满足一下几个要点:

  • 遇到有效字符(+,-,0-9)前的空白符直接跳过
  • 遇到非空白符非有效字符那么直接输出已经构造的数字(比如遇到字母)
  • 遇到有效字符后除非遇到数字,不然直接输出已经构造的数字(比如-+2,输出0,+2-4输出2)
int myAtoi(string str) {
    long result = 0;
    int sign = 1;
    bool show = false;  //遇到有效字符的标记,一但遇到有效字符就将该标记置为true
    for (int i = 0; i < str.size(); i++) {
        if ((str[i] - '0') >= 0 && (str[i] - '0') <= 9) {
            result = 10 * result + str[i] - '0';
            show = true;
        }
        else if (show) //遇到有效字符后,除非是数字,不然就break
            break;
        else if (str[i] == '-') {
            sign = -1;
            show = true;
        }
        else if (str[i] == '+')
            show = true;
        else if (str[i] == '\n' || str[i] == '\r' || str[i] == ' ')
            continue;
        else  //其余情况一律break
            break;
        if (result * sign > INT32_MAX)
            return INT32_MAX;
        else if (result * sign < INT32_MIN)
            return INT32_MIN;
    }
    return (int)(result * sign);
}

代码的时间复杂度为 O(n)

总结

这道题并没有考虑8进制和16进制的情况,不过其实处理起来应该差不了多少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值