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 atoi(const char *str) {
if( str == NULL || *str == '\0')
return 0;
long long res = 0;
bool neg = false;
int i = 0;
for( ; *(str+i) == ' '; ++i){}
if( *(str+i) == '+')
++i;
else if( *(str +i) == '-'){
neg = true;
++i;
}
else
;
for( ; *(str + i) != '\0'; ++i){
if( isdigit(*(str+i))){
res = res * 10 + *(str + i) - '0';
}
else
break;
if( res > INT_MAX){//数的大小超过int的范围,就返回边界值
if( neg)
return INT_MIN;
else
return INT_MAX;
}
}
return neg ? -res : res;
}
};