class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0 || str.trim().length() == 0) {
return 0;
}
str = str.trim();
char first = str.charAt(0);
if (!Character.isDigit(first) && first != '+' && first != '-') { // 不是数字,不是符号
return 0;
}
long value = 0;
boolean negative = false; // 符号
if (first == '-') {
negative = true;
} else if (Character.isDigit(first)) {
value = first - '0';
}
char[] strArray = str.toCharArray();
int index = 0;
for (int i = 1; i < strArray.length; i++) {
if (Character.isDigit(strArray[i])) {
value = value * 10 + strArray[i] - '0';
index++;
} else {
break;
}
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) { // 防止long也超了
break;
}
}
if (negative) {
value = -value;
}
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)value;
}
}