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) {
long long value = 0;
bool flag = true;
while(*str == ' '){//去掉前面的空格
str++;
}
if(*str == '+'){
str++;
}
if(*str == '-'){
flag = false;
str++;
}
while(*str >='0' && *str <= '9'){
value = value * 10 + *str - '0';
str++;
}
value = flag == true ? value : -value;
if (value < INT_MIN ) {
return INT_MIN ;
} else if (value > INT_MAX ) {
return INT_MAX ;
} else {
return (int)value;
}
}
};