1. public static int parseInt(String s, int radix)
a. 充分考虑各种异常情况:字符串为空,带符号,进制出界,计算值出界
b. 计算时转换为负数进行处理:
Integer.MIN_VALUE直接变换符号会导致数值溢出
Integer.MAX_VALUE = 0x7fffffff (+2147483647)
Integer.MIN_VALUE = 0x80000000 (-2147483648, -10000000000000000000000000000000)
= Integer.MAX_VALUE + 1 = Math.abs(Integer.MIN_VALUE) = -1 * Integer. // 最大整数加1后等于最小整数
public static int abs(int a) { return (a < 0) ? -a : a; } // 注意如果参数等于Integer的最小值,将返回相同的值。
public static int parseInt(String s, int radix) throws NumberFormatException { /* * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. */ 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"); } int result = 0; boolean negative = false; int i = 0, len = s.length(); int limit = -Integer.MAX_VALUE; int multmin; int digit; 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); if (len == 1) // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s); i++; } multmin = limit / radix; while (i < len) { // 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); } return negative ? result : -result; }
2. static int stringSize(int x)
使用常量穷举,避免除法和求余等计算
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; // Requires positive x static int stringSize(int x) { for (int i=0; ; i++) if (x <= sizeTable[i]) return i+1; }