Java Study--Interger.parseInt(String s, int radix)

Interget.parseInt(String s, int radix)实现原理。
源码:

 public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
     	... // 参数合法性检查,省略
        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;
		
		// 假设输入eg="25"
        if (len > 0) {
            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);
				// eg不在上两个 if else 中,negative = false
				
                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            } 
            multmin = limit / radix;
            // 从string的第一个char开始循环向后取
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                
                // Character.digit(char ch, int radix),在这里的效果,对char '0'~'9'返回int 0~9
                // digit方法针对ascii字符的优化
                // if ('0' <= codePoint && codePoint <= '9') {
             	//   result = codePoint - '0';
				//  } else if ('a' <= codePoint && codePoint <= 'z') {
         	    //     result = 10 + (codePoint - 'a');
           	    //	} else if ('A' <= codePoint && codePoint <= 'Z') {
                //     result = 10 + (codePoint - 'A');
            	//  }
            	
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                // 假设之前是 -2,对应‘2’,radix=10,当前值为5,对应‘5’
                result *= radix; //效果相当于将之前获得的值进位(result是负数对应正数真实值)
                // 变成 -2*10
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
                // 变成 -2*10-5= -25
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        // 根据正负性返回result的正数或负数,(result是负数对应正数真实值)
        return negative ? result : -result;
        // negative为false,返回 -(-25)=25
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值