8 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

把字符串转换成整数,和剑指offer 49题相似,不过这里的要求比较多,实现atoi

  • 判断开头是否有空格
  • 判断开头是否有 '+','-'
  • 如果遇到非法字符返回已有的结果
  • 如果超过边界,返回边界值

class Solution {
public:
    int myAtoi(string str) {
        int len = str.size();
        if (len==0) return 0;
        int res = 0;
        bool flag = false;
        int start = 0;
        //判断第一个非空格位置
        while (str[start]==' ') ++start;
        for (int i = start;i<len;i++)
        {
            if (i==start&&str[i]=='-')
                flag = true;
            else if (i==start && str[i]=='+')
                continue;
            else if (str[i]>='0' && str[i]<='9')
            {
                //2147483647最后一位为7
                if (res > INT_MAX/10 || (res==INT_MAX/10&&(str[i]-'0')>7))
                {
                    //返回边界值
                    return flag?INT_MIN:INT_MAX;
                }
                res = res*10+str[i]-'0';
            }
            //遇到非法字符返回已有的结果
            else
            {
                if (flag)
                    res *= -1;
                return res;
            }
        }
        if (flag)
            res *= -1;
        return res;
    }
};

 
comments powered by Disqus