private static int stringToInt(String str) throws Exception {
boolean isNegative = false;
long value = 0;
if (str == null || str == “”)
throw new Exception(“null”);
for (int i = 0; i < str.length(); i++) {
if (i == 0 && (str.charAt(i) == ‘-’ || str.charAt(i) == ‘+’)) {
if (str.charAt(i) == ‘-‘) {
isNegative = true;
}
} else if (str.charAt(i) >= ‘0’ && str.charAt(i) <= ‘9’) {
value = value * 10 + (str.charAt(i) - ‘0’);
if ( (!isNegative && value > Integer.MAX_VALUE)
|| (isNegative && ((value - Long.parseLong(String.valueOf(Integer.MAX_VALUE))) > 1)))
throw new Exception(“out of range”);
} else {
throw new Exception(“error”);
}
}
return (int) (isNegative ? -1 * value : value);
}
autoi java实现
最新推荐文章于 2024-11-03 21:27:26 发布