注意判断是否>INT_MAX or <INT_MIN
时间复杂度:O(N)
C++代码:
class Solution {
public:
int myAtoi(string str) {
int flag = 0, num = 0;
for (int i = 0; i < str.length(); i++)
{
if (!flag && str[i] == ' ')
continue;
else
{
if (!flag)
{
if (str[i] == '+')
flag = 1;
else if (str[i] == '-')
flag = -1;
else if ((str[i] - '0') < 0 || (str[i] - '0') > 9)
return 0;
else
{
num += str[i] - '0';
flag = 1;
}
}
else
{
if ((str[i] - '0') < 0 || (str[i] - '0') > 9)
{
break;
}
else
{
if (flag == 1 &&
(num > INT_MAX / 10 ||
(num == INT_MAX / 10 && (str[i] - '0') > 7)))
return INT_MAX;
else if (flag == -1 &&
(flag*num < INT_MIN / 10 ||
(flag * num == INT_MIN / 10 && (str[i] - '0') > 8)))
return INT_MIN;
num = num * 10 + (str[i] - '0');
}
}
}
}
return num * flag;
}
};