Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
这题很讨厌,要考虑所有的情况,可以拿标准函数atoi做测试,看它输出的是什么结果。
int myAtoi(char* str) {
if (str == NULL)
return 0;
int len = strlen(str);
int k = 0;
if (str[0] != ' ' && str[0] != '+' && str[0] != '-' && !(str[0] - '0' >= 0 && str[0] - '9' <= 0))
return 0;
while (k<len&&str[k]== ' ' )
k++;
if (k == len)
return 0;
bool positive = true;
long long int re = 0;
if (str[k] == '+' || str[k] == '-')
{
if (k == len - 1)
return 0;
if (!(str[k + 1] - '0' >= 0 && str[k + 1] - '9' <= 0))
return 0;
if (str[k] == '-')
positive = false;
k++;
}
long long int intmax = 2147483647;
//#define INT_MIN (-2147483647 - 1)
//long long int intmin = -2147483648;
while (k < len&&str[k]-'0'>=0&&str[k]-'9'<=0)
{
re = 10 * re + str[k] - '0';
if (positive&&re > intmax)
{
re = intmax;
break;
}
if (!positive&&re > intmax + 1)
{
re = intmax + 1;
break;
}
k++;
}
return positive ? re : -re;
}
accepted