链接:https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
代码
class Solution {
public:
int strToInt(string str) {
int k = 0;
while (k < str.size() && str[k] == ' ') k++;
long long number = 0;
bool is_minus = false;
if (str[k] == '+') k++;
else if (str[k] == '-') k++, is_minus = true;
while (k < str.size() && str[k] >= '0' && str[k] <= '9') {
int t = str[k] - '0';
if (number > INT_MAX / 10 || (number == INT_MAX / 10 && t > 7)) {
return is_minus ? INT_MIN : INT_MAX;
}
number = number * 10 + t;
k++;
}
if (is_minus) number *= -1;
return (int)number;
}
};