要求:
1. 舍弃前导空格
2. 判断符号位
3. 溢出判断
感觉意义不大,,,边界条件判断思想还是可以的。
class Solution {
public:
int convert(char x){
return x-'0';
}
int myAtoi(string str) {
int res = 0, bndry = INT_MAX / 10;
int i = 0, sign = 1, length = str.size();
if(length == 0) return 0;
//空格处理
while(str[i] == ' ')
if(++i == length) return 0;
//处理符号位
if(str[i] == '-') sign = -1;
if(str[i] == '-' || str[i] == '+') i++;
for(int j = i; j < length; j++) {
if(str[j] < '0' || str[j] > '9') break;
//边界处理:
// 1. res > INT_MAX / 10
// 2. res = INT_MAX / 10 && 下一位大于7
if(res > bndry || res == bndry && str[j] > '7')
return sign == 1 ? INT_MAX : INT_MIN;
res = res * 10 + (str[j] - '0');
}
return sign * res;
}
};