题解
考虑如下条件:
- 空字符串,返回 0;
- 第一个数字前是 ‘+’ 或者 ‘-‘;
- 数字前有空格;
- 转换过程中,遇到第一个非数字字符,停止转换。
- int 范围在
[-2147483648, 2147483647]
,超过这个范围返回相应的INT_MAX
,INT_MIN
class Solution {
public:
int myAtoi(string str) {
if(str.empty()) return 0;
bool isNegative = false;
int i = 0, j = 0;
while(str[j] == ' ') j++;
i = j;
if(str[j] == '-') isNegative = true, i = j + 1;
if(str[j] == '+') i = j + 1;
long long num = 0;
for(; i < str.length(); ++i){
if(isdigit(str[i])) {
num = num * 10 + (str[i] - '0');
if(num > INT_MAX) return isNegative ? INT_MIN : INT_MAX;
}
else break;
}
return isNegative ? -num : num;
}
};