学习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) {//控制溢出
             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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值