8 字符串转整数aoti

注意"+42"返回值是42

// 注意"+42"返回值是42
class Solution {
public:
    int myAtoi(string str) {
        long long ans = 0;
        int i = 0, sign = 1;
        // 先清空字符串前缀空格
        while(str[i] == ' ') ++i;
        if(str[i] == '+') ++i;
        else if(str[i] == '-') sign = -1, ++i; // 符号为负
        while(i < str.size() && str[i] >= '0' && str[i] <= '9')
        {
            ans = 10 * ans + (str[i] - '0');
            if(ans > (long long)INT_MAX && sign == 1) return INT_MAX; // 退出
            if(ans > (long long)INT_MAX + 1 && sign == -1) return INT_MIN;
            ++i;
        }
        ans *= sign;
        return ans;
    }
};

你可能感兴趣的:(Leetcode)