美文网首页
剑指offer | 字符串转为整形

剑指offer | 字符串转为整形

作者: icebreakeros | 来源:发表于2019-08-01 09:02 被阅读0次

字符串转为整形

Integer.parseInt()方法源码

public class StringToInt {

    public int parseInt(String s, int radix) throws NumberFormatException {
        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                    " greater than Character.MAX_RADIX");
        }

        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        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 forInputString(s, radix);
                }

                if (len == 1) { // Cannot have lone "+" or "-"
                    throw forInputString(s, radix);
                }
                i++;
            }
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw forInputString(s, radix);
                }
                System.out.println("i: " + i + ", digit = " + digit);
                result *= radix;
                if (result < limit + digit) {
                    throw forInputString(s, radix);
                }
                System.out.println("i: " + i + ", result *= radix : " + result);
                result -= digit;
                System.out.println("i: " + i + ", result -= digit : " + result);
            }
            return negative ? result : -result;
        } else {
            throw forInputString(s, radix);
        }
    }

    private NumberFormatException forInputString(String s, int radix) {
        return new NumberFormatException("For input string: \"" + s + "\"" +
                (radix == 10 ?
                        "" :
                        " under radix " + radix));
    }
}

相关文章

网友评论

      本文标题:剑指offer | 字符串转为整形

      本文链接:https://www.haomeiwen.com/subject/qrvfdctx.html