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.
思路:主要考察边界条件的测试。字符串前几个若为空格则跳过。加减符号另行考虑。且正数的最大界与负数的最小界也要考虑进去。正负数时对于前一次运行结果分别使用加减。
class Solution {
public:
int myAtoi(string str) {
bool g_nStatus = false;
const char* digit = str.c_str();
long long num = 0;
if(digit == NULL)
return false;
else
{
while(*digit == ' ')
digit++;
bool minus = false;
if(*digit == '+')
digit++;
else if(*digit == '-')
{
digit++;
minus = true;
}
while(*digit != '\0')
{
if(*digit >= '0' && *digit <='9')
{
num = num * 10 + (*digit - '0');
if(num > std::numeric_limits<int>::max())
{
num = 0;
break;
}
digit++;
}
else
{
num = 0;
break;
}
}
if(*digit != NULL)
{
g_nStatus = true;
if(minus)
num = 0 - num;
}
}
return num;
}
};