跳转至

字符串转换整数 (atoi)⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int myAtoi(string s) {
        int index = 0;
        int n = s.size();
        while (index < n && s[index] == ' ') index++;

        int res = 0;
        int sign = 1;

        if (index < n && s[index] == '+') {
            sign = 1;
            index++;
        } else if (index < n && s[index] == '-') {
            sign = -1;
            index++;
        }

        while (index < n && isdigit(s[index])) {
            int digit = s[index] - '0';
            if ((res > INT_MAX / 10) || (res == INT_MAX / 10 && digit > INT_MAX % 10)) {
                return sign == 1 ? INT_MAX : INT_MIN;
            }

            res = 10 * res + digit;
            index++;
        }

        return res * sign;
    }
};