學習Java庫的parseInt

在找工作面試的時候有朋友被要求寫一個atoi的程序。考慮的細節相當多,要寫好這樣一個函數絕不是容易的事情。後來和朋友一起學習了Java庫的parseInt,寫得真是妙極了。Java中parseInt不考慮前導零和多餘的加號。主要考慮字符錯,溢出。這裏好好學習一下。下面先是測試用例:
     * parseInt("0", 10) returns 0
     * 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
源代碼如下:
public static int parseInt(String s, int radix) throws NumberFormatException
 {
     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) {//控制溢出
       

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章