package test;
public class AtoiTest {
public static void main(String[] args) {
String str = "-2147483649";
long num = 0;
try {
num = strToInt(str);
System.out.print(num);
} catch (Exception e) {
e.printStackTrace();
}
}
private static long strToInt(String str) throws Exception {
long number = 0;
char num[] = str.toCharArray();
int valid;
if ('-' == num[0]) {
valid = -1;
if (num.length > 11) {
throw new Exception("超过整数范围");
}
} else {
valid = 0;
if (num.length > 10) {
throw new Exception("超过整数范围");
}
}
for (int i = 0; i < num.length; i++) {
if (valid == 0) {
if (num[i] >= '0' && num[i] <= '9') {
number = 10 * number + (num[i] - '0');
if (num[0] == '-' && (-number) <Integer.MIN_VALUE){
throw new Exception("超过整数范围");
} else if(number >Integer.MAX_VALUE) {
throw new Exception("超过整数范围");
}
} else {
throw new Exception("非数字字符");
}
} else {
valid = 0;
continue;
}
}
if ('-' == num[0]) {
return -number;
}
return number;
}
}
java atoi实现
最新推荐文章于 2022-05-01 09:34:14 发布