字符串转整数
- 空格处理
- 正负号处理
- 读入数字 res = res*10 + num;(注意溢出)
定义i偏移量,字符串长度
定义结果和符号正负
定义越界 INT_MAX/10
省去空格
判断正负号
省去正号负号
循环复制给res 并判断下次运算是否越界 越界的话,返回最小/最大值
退出循环,返回结果乘以符号位
代码:
class Solution {
public:
int myAtoi(string s) {
if (s.empty()) {
return 0;
}
int i = 0, len = s.length();
int res = 0, firstChar = 1;
int upperBound = INT_MAX / 10;
while (s[i] == ' ') {
if (++i >= len) {
return 0;
}
}
if (s[i] == '-') {
firstChar = -1;
}
if (s[i] == '+' || s[i] == '-') {
i++;
}
for (; i < len; ++i) {
if (s[i] < '0' || s[i] > '9') {
break;
}
if (res > upperBound || (res == upperBound && s[i] > '7')) {
return firstChar == 1 ? INT_MAX : INT_MIN;
}
res = res * 10 + (s[i] - '0');
}
return firstChar * res;
}
};