讨论/《图解算法数据结构》 - 剑指 Offer 67. 把字符串转换成整数/
《图解算法数据结构》 - 剑指 Offer 67. 把字符串转换成整数

Cpp:

int CheckNum(char c)
{
    if(c<='9' && c>='0')
        return c - '0';
    return 0;
}

class Solution {
public:
    int strToInt(string str) {
        bool IsNonSpace = false;
        bool IsFirstSign = false;
        bool IsPositive = true;
        bool IsWithinNum = false;
        int num = 0;
        for(auto &x:str)
        {
            if(x==' ')
            {
                if(IsWithinNum || IsFirstSign)
                    break;
                continue;
            }else if(x == '+' || x=='-'){
                if(IsNonSpace || IsFirstSign || IsWithinNum)
                    break;
                IsFirstSign = true;
                if(x=='-')
                    IsPositive = false;
                continue;
            }else if(CheckNum(x) || x=='0'){
                IsWithinNum = true;
                if(IsNonSpace)
                    break;
                if(num<=(INT_MAX-CheckNum(x))/10)
                    num = num * 10 + CheckNum(x);
                else return IsPositive?INT_MAX:-INT_MAX-1;
                continue;
            }
            else{
                IsNonSpace = true;
                if(IsFirstSign==true)
                    break;
            }

        }
        return IsPositive?num:-num;
    }
};
1
展开全部 9 讨论