public class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
// trim the whitespace
str = str.trim();
boolean positive = true;
// check positive or negative
int i = 0;
if (str.charAt(i) == '-') {
positive = false;
i++;
} else if (str.charAt(i) == '+') {
i++;
}
// avoid overflow
double result = 0;
// calculate value
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
if (positive) {
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
} else {
if (-result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
i++;
}
if (!positive) {
result = - result;
}
return (int) result;
}
}