class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
int StrToInt(string s) {
// write code here
int n = s.size(), i = 0, sign = 1;
long long res = 0;
// 1) 跳过前导空格
while (i < n && s[i] == ' ') ++i;
if (i == n) return 0;
// 2) 符号
if (s[i] == '+' || s[i] == '-') {
if (s[i] == '-') sign = -1;
++i;
}
// 3) 读数字,遇到非数字停止;期间做溢出保护
bool has = false;
while (i < n && s[i] >= '0' && s[i] <= '9') {
has = true;
int d = s[i] - '0';
res = res * 10 + d;
if (sign == 1 && res > INT_MAX) return INT_MAX;
if (sign == -1 && -res < INT_MIN) return INT_MIN;
++i;
}
// 4) 无有效数字返回 0
if (!has) return 0;
return sign * res;
}
};