Integer.parseInt(String string,int radix) String 转 Intege
输入参数:
转换字符串 string,转换后进制 radix
实现思路:
- 是否为空
if (s == null) {
throw new NumberFormatException("null");
}
- 进制是否支持 MIN_RADIX 2~ MAX_RADIX 36
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
- 判断正负号
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
- 数字转换与进制转换(使用的Character.digit 转换数字)
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
- 返回
return negative ? result : -result;
为什么以负数形式来增加,int limit = -Integer.MAX_VALUE; 是所能解析数的最大范围。
int 范围: − 2 32 {-2^{32}} −232 ~ 2 32 − 1 {2^{32}-1} 232−1
由于 结果是 负号 + 数字,所以如果以正数来记录,当数字等于 − 2 32 {-2^{32}} −232
那么 会溢出。
所以是为了防止溢出
自己试试
public static int parseInt(String str){
// check null
if(str == null)
throw new NumberFormatException("str is null");
boolean negative = false;
boolean signed = false;
// check signed
if(str.charAt(0) == '-') {
negative = true;
signed = true;
}
else if(str.charAt(0) == '+'){
signed = true;
}
// check length
if(signed){
String ckStr = str.substring(1);
if(ckStr.compareTo("2147483648") == 1 && negative)
throw new NumberFormatException("Out of the range of Integer-!");
else if(ckStr.compareTo("2147483647") == 1 && !negative)
throw new NumberFormatException("Out of the range of Integer+!");
}
else {
if(str.compareTo("2147483648") == 1 && negative)
throw new NumberFormatException("Out of the range of Integer!");
else if(str.compareTo("2147483647") == 1)
throw new NumberFormatException("Out of the range of Integer!");
}
// parse
// note: ASCII '0' : 48
int i = 0;
if(signed)
i++;
int res = 0;
while (i < str.length()){
int asciiNum = (int)str.charAt(i++);
if(asciiNum < 48 || asciiNum > 57)
throw new NumberFormatException("String cannot be Integer");
res *= 10;
res -= asciiNum - 48;
}
return negative? res : -res;
}