输入类型可以为 +xxxx -xxxxx 1231231fasfaf adassf4343 -124414141414214 +124114141241414 只会检测 前部分转换
public static int strToInt(String str) {
str = str.trim();
int len = str.length();
if(len == 0) return 0;
int index = 0;
int sign = 1;
if(str.charAt(index) == '-' || str.charAt(index) == '+'){
sign = str.charAt(index) == '+' ? 1 : -1;
index ++;
}
int res = 0;
for(; index < len; index++){
int digit = str.charAt(index) - '0';
if(digit < 0 || digit > 9) break;
if(res > Integer.MAX_VALUE/10 || res == Integer.MAX_VALUE/10 && digit > Integer.MAX_VALUE%10){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + digit;
}
return sign * res;
}
|