将 string 转化为 int。规则如下:
- string 中允许 leading space
- 可以存在正负号
- string 中前一部分是可以转化为 int 的表达,后一部分可以是任意 characters, ignore and this is valid
- if invalid string, return 0
- if string value is greater than Integer.MAX or less than Integer.MIN,return Integer.MAX / Integer.MIN
public int myAtoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
int len = str.length();
int index = 0;
while (index < len && str.charAt(index) == ' ') {
index++;
}
int sign = 1;
if (index < len && (str.charAt(index) == '-' || str.charAt(index) == '+')) {
sign = (str.charAt(index++) == '-') ? -1 : 1;
}
// invalid case
if (index == len || str.charAt(index) > '9' || str.charAt(index) < '0') {
return 0;
}
int res = 0;
int maxValue = Integer.MAX_VALUE / 10;
int lastDigitMax = (sign < 0) ? 8 : 7;
while (index < len && str.charAt(index) >= '0' && str.charAt(index) <= '9') {
int digit = (int)(str.charAt(index) - '0');
if ((res > maxValue) || (res == maxValue && digit > lastDigitMax)) {
return (sign > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + digit;
index++;
}
return (sign < 0) ? -res : res;
}
网友评论