Write your own 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.
int myAtoi(string str) {
int sign = 1, base = 0, i = 0;
// 1. Discard empty space
while (str[i] == ' ') i++;
// 2. Optional initial plus or minus sign
if (str[i] == '-') {
sign = -1, i++;
} else if (str[i] == '+') {
sign = 1, i++;
}
// 3. Convert digit char to integer
while (isdigit(str[i])) {
int temp = 10*base + str[i++] - '0';
// 4. Check for overflow
if (temp/10 != base) {
return sign == 1 ? INT_MAX : INT_MIN;
}
base = temp;
}
return base * sign;
}