* parseInt("473", 10) returns 473
* parseInt("-0", 10) returns 0
* parseInt("-FF", 16) returns -255
* parseInt("1100110", 2) returns 102
* parseInt("2147483647", 10) returns 2147483647
* parseInt("-2147483648", 10) returns -2147483648
* parseInt("2147483648", 10) throws a NumberFormatException
* parseInt("99", 8) throws a NumberFormatException
* parseInt("Kona", 10) throws a NumberFormatException
* parseInt("Kona", 27) returns 411787
{
if (s == null) { //s不爲空,這個檢驗很重要,面試的時候很看重
throw new NumberFormatException("null");
}
int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit; //以負數來控制溢出
int multmin; //精彩絕倫的是這兩個變量的使用,
int digit;
if (max > 0) {
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE; //負數時向下溢出的最小值
i++;
} else {
limit = -Integer.MAX_VALUE;//正數時向上溢出的最大值的負
}
multmin = limit / radix; //再讀入一位數字時的對已有累積數的控制
if (i < max) { //這個if條件事實上可以整合到下面的while中,單獨寫的原因猜可能是爲了省while中的兩個if條件和一個乘法的執行時間。以代碼長度來換取時間?
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
} else {
result = -digit; //看,初始化爲負數
}
}
while (i < max) {
// 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) {//控制溢出