8. String to Integer (atoi)
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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
Code:
int myAtoi(char* str) {
if(!str)
return 0;
int sign = 1;
int num = 0;
while(*str == ' ')
str++;
if(*str == '+')
str++;
else if(*str == '-')
{
sign = -1;
str++;
}
while(*str!=' ')
{
if(*str == '+'||*str == '-')
return 0;
else if(*str<'0'||*str>'9')
return num*sign;
if (num > INT_MAX / 10)
return sign == 1? INT_MAX : INT_MIN;
num*=10;
if ((*str - '0') > (INT_MAX - num))
return sign == 1? INT_MAX : INT_MIN;
num = num + *str - '0';
str++;
}
return num*sign;
}