class Solution {
private final static long INT_MAX = 2147483647l;
private final static long INT_MIN = -2147483648l;
public int strToInt(String str) {
long res = 0;
long intStatus = 1;
int status = 0;
for (int i = 0; i < str.length(); i++) {
switch (status) {
case 0:
if (str.charAt(i) == ' ') {
continue;
} else if (str.charAt(i) == '+' || str.charAt(i) == '-') {
if (str.charAt(i) == '-') {
intStatus = -1;
}
status = 1;
} else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
res *= 10;
res += str.charAt(i) - '0';
status = 2;
} else {
status = 3;
}
break;
case 1:
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
res *= 10;
res += str.charAt(i) - '0';
status = 2;
} else {
status = 3;
}
break;
case 2:
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
res *= 10;
res += str.charAt(i) - '0';
status = 2;
} else {
status = 3;
}
break;
case 3:
if (res * intStatus > INT_MAX) {
return (int)INT_MAX;
}
if (res * intStatus < INT_MIN) {
return (int)INT_MIN;
}
return (int)(res * intStatus);
default:
break;
}
if (res * intStatus > INT_MAX) {
return (int)INT_MAX;
}
if (res * intStatus < INT_MIN) {
return (int)INT_MIN;
}
}
return (int)(res * intStatus);
}
}