**Alway failed on "2147483648".
But when I test it locally, it's fine.**

class Solution {

public:

int atoi(const char *str) {

if (str == NULL || *str == '\0') {

// return 0 when invalid

return 0;

}

```
int state = 0;
int sign = 1;
long int num = 0;
while (*str != '\0') {
switch (state) {
case 0: // skip spaces
if (isspace(*str)) {
} else if (isdigit(*str)) {
num += *str - '0';
state = 1;
} else if (*str == '+' || *str == '-') {
if (*str == '-')
sign = -1;
state = 2;
} else {
return 0;
}
str++;
break;
case 1: // digit found
if (isdigit(*str)) {
num = num*10 + *str - '0';
if (num*sign < INT_MIN) {
return INT_MIN;
} else if (num*sign > INT_MAX) {
return INT_MAX;
}
} else {
return sign*num;
}
str++;
break;
case 2: // sign found
if (isdigit(*str)) {
num += *str - '0';
state = 1;
} else {
return 0;
}
str++;
break;
}
}
if(state == 1) {
return sign*num;
} else {
return 0;
}
}
```

};