public int atoi(String str) {
int f = 1;
int result = 0;
boolean start = false;
for (int i = 0; i < str.length(); ++i) {
if (start) {
if (str.charAt(i) < '0' || str.charAt(i) > '9') {
break;
} else {
if (f == 1 && result >= Integer.MAX_VALUE / 10) {
if (result > Integer.MAX_VALUE / 10
|| (str.charAt(i) - '0') > Integer.MAX_VALUE % 10) {
return Integer.MAX_VALUE;
}
} else if (f == -1 && f * result <= Integer.MIN_VALUE / 10) {
if (f * result < Integer.MIN_VALUE / 10
|| (str.charAt(i) - '0') > (0 - (Integer.MIN_VALUE % 10))) {
return Integer.MIN_VALUE;
}
}
result = result * 10 + (str.charAt(i) - '0');
}
} else {
if (str.charAt(i) == ' ') {
continue;
} else if (str.charAt(i) == '-') {
f = -1;
} else if (str.charAt(i) == '+') {
f = 1;
} else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = str.charAt(i) - '0';
} else {
break;
}
start=true;
}
}
return f * result;
}
}
atoi
最新推荐文章于 2022-03-31 19:07:25 发布