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.
class Solution {
public:
int atoi(const char *str) {
long long num = 0;
int sign = 1;
const char *stemp = str;
if (stemp == NULL)
{
return 0;
}
while(*stemp == ' ')
{
stemp++;
}
if (*stemp == '+')
{
stemp++;
}
else if (*stemp == '-')
{
sign = -1;
stemp++;
}
while(*stemp == '0')
{
stemp++;
}
while (*stemp >= '0' && *stemp <= '9')
{
num = num * 10 + *stemp - '0';
if (num * sign > INT_MAX)
return INT_MAX;
if (num * sign < INT_MIN)
return INT_MIN;
stemp++;
}
return num * sign;
}
};