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 atoi(const char *str) {
if(!str)return 0;
int sign = 1, i = 0,prev;
long long res = 0;
while(str[i] == ' ' || str[i] == '\t')i++;
if(str[i] == '-'){sign = -1;i++;}
else if (str[i] == '+')i++;
while(str[i])
{
int x = str[i]-48;
if(x<0 || x>9 )return (res*sign);prev = res;
res = (res<<3) + (res<<1) + x;
if(res > 2147483647){if(sign == -1)return -2147483648; else return 2147483647;}
i++;
}
return ((int)res*sign);
}
No comments:
Post a Comment