class Solution {
public:
int myAtoi(string s) {
int sign = 1;
long long result = 0; // ✅ 初始化!
int i = 0;
int n = s.length();
// 跳过前导空格
while (i < n && s[i] == ' ') {
i++;
}
// 检查正负号(修正逻辑运算符)
if (i < n && (s[i] == '-' || s[i] == '+')) { // ✅ 加上括号
sign = (s[i] == '+') ? 1 : -1;
i++;
}
// 读取数字
while (i < n && isdigit(s[i])) {
int digit = s[i] - '0'; // ✅ 修正拼写
// 检查溢出
if (result > INT_MAX / 10 ||
(result == INT_MAX / 10 && digit > INT_MAX % 10)) {
return (sign == 1) ? INT_MAX : INT_MIN; // ✅ 直接返回
}
result = result * 10 + digit;
i++;
}
return result * sign;
}
};