思路:把示例中的几种情况考虑到就可以了
public int myAtoi(String str) {
if (str == null) {
return 0;
}
// 忽略首尾空格
str = str.trim();
if (str.length() == 0) {
return 0;
}
// 首字母是数字,正号,负号
char c = str.charAt(0);
int iVal = 0;
int sign = 1;
if ('-' == c) {
sign = -1;
} else if ('+' == c) {
} else if (c >= '0' && c <= '9') {
iVal = (c - '0');
} else {
return 0;
}
for (int i = 1; i < str.length(); i++) {
char tmpC = str.charAt(i);
if (tmpC < '0' || tmpC > '9') {
break;
}
int newVal = 10 * iVal + (tmpC - '0');
if (iVal > newVal || iVal > 214748364) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
iVal = newVal;
}
return sign * iVal;
}