学习Java库的parseInt

来源:互联网 发布:网络数据库技术 编辑:程序博客网 时间:2024/06/06 17:53
在找工作面试的时候有朋友被要求写一个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) {//控制溢出
             throw NumberFormatException.forInputString(s);
         }
         result -= digit; //用减法,不像我们一样用加法
      }
   } else {
     throw NumberFormatException.forInputString(s);
   }
   if (negative) {
      if (i > 1) {
         return result;
      } else { 
         throw NumberFormatException.forInputString(s);
      }
   } else {
     return -result;
   }
}

0 0
原创粉丝点击