【一天一道LeetCode】#8. String to Integer (atoi)

一天一道LeetCode系列

(一)题目

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.

Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char* argument, please click the reload button to reset your code definition.

(二)解题

分析特殊情况:
1、字符前面有空格,“ 010”
2、数字前或者中间出现了其他的字符“b123”,“ -012b12123”
3、数字越界,int是-2147483648到2147483647
4、最奇葩的+-2,我觉得应该输出-2,可是leetcode上显示输出0。

class Solution {
public:
    int myAtoi(string str) {
        long lresult=0;
        int i = 0;
        int max=2147483647;
        int min=-2147483648;
        bool isNegetive  = false;
        while(str[i] != '\0' && str[i] ==' ') i++;//判断前面是空格的情况
        if(str[i] == '-') {isNegetive = true;i++;}//判断正负
        else if(str[i] == '+'){i++;}

        while(i<str.length())
        {
            if(str[i]>='0' && str[i]<='9')
            {
                lresult*=10;
                lresult+=(str[i] - '0');
                i++;
            }
            else break;//出现其他字符干扰则退出循环
            //检查越界情况
            long lresult_temp = (isNegetive == true) ?-lresult:lresult;
            if(!isNegetive&&lresult_temp>=max) return max;
            if(isNegetive&&lresult_temp<=min) return min;
        }
        return (isNegetive == true) ?-lresult:lresult;//输出结果

    }
};

感觉做这道题还是自己考虑的情况不够多,总是遗漏了一些特殊情况。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值