[LeetCode]8. String to Integer (atoi)

原题链接:https://leetcode.com/problems/string-to-integer-atoi/description/

[LeetCode]8. String to Integer (atoi)

[LeetCode]8. String to Integer (atoi)

意思是把输入的字符串string转为int。然后会有错误输入,要对这些进行处理。具体要求为Requirements for atoi: 

我的实现:

class Solution {
public:
    int myAtoi(string str) {
        bool initialSign = true;
        bool isPositive = true;
        int result = 0;
        
        for (int i = 0; i < str.length(); i++) {
            if (str[i] == '+' && initialSign) {
                isPositive = true;
                initialSign = false;
            } else if (str[i] == '-' && initialSign) {
                isPositive = false;
                initialSign = false;
            } else if (str[i] >= '0' && str[i] <= '9') {
                if ((abs(result) > (INT_MAX / 10) && isPositive) || (abs(result) == (INT_MAX / 10) && str[i] > '7' && isPositive)) 
                    return INT_MAX;
                else if ((abs(result) > (INT_MAX / 10) && !isPositive) || (abs(result) == (INT_MAX / 10) && str[i] > '8' && !isPositive)) 
                    return INT_MIN;
                result = result * 10 + (str[i] - '0');
                initialSign = false;
            } else if (!initialSign || str[i] != ' ') {
                return isPositive ? result : -1*result;
            }
        }
        
        return isPositive ? result : -1*result;
    }
};

总结:仔细考虑错误输入,溢出处理同[LeetCode]7. Reverse Integer