最近看剑指 Offer,最后的面试案例有一道字符串转整形的题,虽然题本身不难,但是需要考虑很多特殊情况,包括参数为空字符串、null 以及溢出等。
好奇看了一下 Java 源码中 Integer 类的 parseInt() 方法的实现(valueOf() 方法调用了parseInt() 方法),发现这个实现对于溢出的处理很巧妙,故在此处记录一下。
之前自己实现字符串转整形的方法时,用 long 来表示最后转换完的结果,然后再强转成 int 型,这样可以方便的处理溢出的情况。
// 部分参考了 Integer.parseInt() 的实现 static int strToInt(String str){ if (str == null || str.length() == 0) throw new NumberFormatException(str); long res = 0; boolean negative = false; int len = str.length(); int i = 0; char firstChar = str.charAt(0); if (firstChar < '0'){ if (firstChar == '-'){ negative = true; }else if (firstChar != '+'){ throw new NumberFormatException(str); } if (len == 1){ throw new NumberFormatException(str); } i++; } while(i < len){ char ch = str.charAt(i); if (ch < '0' || ch > '9'){ throw new NumberFormatException(str); } int digit = str.charAt(i++) - '0'; res = res * 10 + digit; if (negative == false && res > Integer.MAX_VALUE){ throw new NumberFormatException(str); } if (negative == true && res - 1 > Integer.MAX_VALUE){ throw new NumberFormatException(str); } } return negative ? -(int)res : (int)res; }