问题原始链接 https://leetcode.com/problems/string-to-integer-atoi
public class Solution {
public static int myAtoi(String str) {
if (str == null) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
if (str.charAt(0) != '+' && str.charAt(0) != '-'
&& !Character.isDigit(str.charAt(0))) {
return 0;
}
if ((str.charAt(0) == '+' || str.charAt(0) == '-')
&& (str.length() == 1 || !Character.isDigit(str.charAt(1)))) {
return 0;
}
int startIndex = str.charAt(0) == '+' || str.charAt(0) == '-' ? 1 : 0;
int sign = str.charAt(0) == '-' ? -1 : 1;
int result = 0;
for (int i = startIndex; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isDigit(c)) {
break;
}
if (result > Integer.MAX_VALUE / 10) {
return Integer.MAX_VALUE;
} else if (result == Integer.MAX_VALUE / 10) {
if (Character.getNumericValue(c) > Integer.MAX_VALUE % 10) {
return Integer.MAX_VALUE;
}
}
if (result < Integer.MIN_VALUE / 10) {
return Integer.MIN_VALUE;
} else if (result == Integer.MIN_VALUE / 10) {
if (sign * Character.getNumericValue(c) < Integer.MIN_VALUE % 10) {
return Integer.MIN_VALUE;
}
}
result = result * 10 + sign * Character.getNumericValue(c);
}
return result;
}
}