LeetCode——字符串转换整数 (atoi)

题目地址:https://leetcode-cn.com/problems/string-to-integer-atoi/

解题思路:注意所有情况。官方提供了类似状态机的一种算法——自动机(https://leetcode-cn.com/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-leetcode-/),这个方法可以避免代码冗余。

int myAtoi(char * str) {
    int i;
    const char tmp[14] = { '0','1','2','3','4','5','6','7','8','9','+','-' ,' '};//模板数组
    long returnS = 0;
    bool flagP = true;//判断正负
    bool flagB = false;//判断是否开始进行转化
    for (i = 0; i < strlen(str); i++)
    {
        int index = strchr(tmp, str[i]) - tmp;//获取下标
        if (strchr(tmp, str[i])) {//如果是有效字符,则处理
            if (index == 12 && !flagB)//空格且第一个出现
                continue;
            else if (index == 11 && !flagB) {//负号且第一个出现
                flagP = false;
                flagB = true;
            }
            else if (index == 10 && !flagB) {//正号且第一个出现
                flagP = true;
                flagB = true;
            }
            else if (index <= 9 && index >= 0 && !flagB) {//数字且第一个出现
                flagP = true;
                flagB = true;
                returnS = 10 * returnS + index;
            }
            else if (flagB && (index == 12 || index == 11 || index == 10)) //转化中途遇到非数字字符
                break;
            else if (flagB && index <= 9 && index >= 0) {
                if (flagP&& returnS > (((long)pow(2.0, 31) - 1) - index) / 10)//判断正数是否溢出
                    return (long)pow(2.0, 31) - 1;
                else if (!flagP &&  -returnS < (-(long)pow(2.0, 31) + index) / 10)//判断负数是否溢出
                    return -(long)pow(2.0, 31);
                else
                    returnS = 10 * returnS + index;
            }
        }
        else
            break;
    }
    return  flagP ? returnS : -returnS;
}
原文地址:https://www.cnblogs.com/cc-xiao5/p/13274246.html