面试官抛出一道编程题:设计一个功能把String转成int,尽量多考虑特殊情况。当时笔者如下作答:用正则表达式替换非数字及正负号进行计算,后来考虑到性能和时间复杂度,又借鉴了Integer.parseInt()的思路,最后编写出一套自己的方法,时间复杂度为O(n)。
经过测试,比Integer.parseInt()的效率要高一点,而且可以忽略非正负号和非数字的字符。但是特殊情况肯定没有标准功能考虑地更全面,不知道Integer.parseInt()具体考虑到了哪些特殊场景,代码奉上:
public class Hello {private static int ADD_ASCII = 43;private static int SUBTRACT_ASCII = 45;private static int ZERO_ASCII = 48;private static int NINE_ASCII = 57;public static void main(String[] args) {String s = "123456789";long start = System.currentTimeMillis();for (int i = 0; i < 1000_0000; i++) {Integer.parseInt(s);}long end = System.currentTimeMillis();long cost = end - start;start = System.currentTimeMillis();for (int i = 0; i < 1000_0000; i++) {convert(s);}end = System.currentTimeMillis();System.out.println("Integer.parseInt()耗时:" + cost + "ms\n" + "convert()耗时:" + (end - start) + "ms");}private static int convert(String str) {if (str == null) {throw new NumberFormatException("The String is null!");}//从前往后判断,如果遇到+-或者数字,结束判断并开始计数int radix = 10;int startIndex = -1;int strLength = str.length();char eachChar;for (int i = 0; i < strLength; i++) {eachChar = str.charAt(i);if (eachChar == ADD_ASCII|| eachChar == SUBTRACT_ASCII|| eachChar >= ZERO_ASCII&& eachChar <= NINE_ASCII) {startIndex = i;break;}}if (startIndex == -1) {throw new NumberFormatException("There is no Number!");}if (startIndex == strLength - 1) {if (str.charAt(startIndex) == ADD_ASCII || str.charAt(startIndex) == SUBTRACT_ASCII) {throw new NumberFormatException("There is no Number!");} else {return str.charAt(startIndex) - ZERO_ASCII;}}boolean negative = true;boolean hasDigit = false;int result = 0;eachChar = str.charAt(startIndex);if (eachChar == ADD_ASCII) {startIndex++;} else if (eachChar == SUBTRACT_ASCII) {startIndex++;negative = false;}//开始计数for (int i = startIndex; i < str.length(); i++) {eachChar = str.charAt(i);if (eachChar >= ZERO_ASCII&& eachChar <= NINE_ASCII) {result = result * radix + eachChar - ZERO_ASCII;if (result < 0) {throw new NumberFormatException("Data is too big for int!");}hasDigit = true;}}if (!hasDigit) {throw new NumberFormatException("There is no Number!");}return negative ? result : -result;}
}
代码运行结果如图: