1. 程式人生 > >不使用JDK的方法自己實現字符串轉整數

不使用JDK的方法自己實現字符串轉整數

for parse 使用 har trim ++ exception int char

暫未考慮正負符號的情況。

    public static int parseInt(String str) {
        if (str == null || str.trim() == "") throw new NumberFormatException("For input string:" + str);
        char[] chars = str.toCharArray();
        long result = 0;
        for (int i = 0; i < chars.length; i++) {
//是否是‘0‘到‘9‘之間的字符
if (chars[i] < ‘0‘ || chars[i] > ‘9‘) throw new NumberFormatException("For input string:" + str);
//先根據字符之間進行運算來得到int值,再根據每個數字所在的位數來計算應該乘10的幾次冪,最後累加。比如【3256=3*1000+2*100+5*10+6】 result
+= (chars[i] - ‘0‘) * Math.pow(10, chars.length - i - 1) ; }
//是否超出int的最大值
if
(result > Integer.MAX_VALUE) throw new NumberFormatException("For input string:" + str); return (int) result; }

不使用JDK的方法自己實現字符串轉整數