自己实现字符串转整数(不使用JDK的字符串转整数的方法)

 【需求】:

(1)如果输入的字符串为null,为空,或者不是数字,抛出异常;

(2)如果输入的数字超出int的最大值或最小值,抛出异常;

(3)输入的数字允许以+或-号开头,但如果输入的字符串只有"+"或"-"号,则抛出异常;

 

 【实现思路】:

关键:字符串 -> 字符 -> 整数。

输入的字符串中的每一个字符都应该是从'0'到'9'这10个字符中的某一个,而这10个字符的ASCII码是有序的,所以后一个字符的ACSII码减去前一个字符的ASCII码一定等于1,根据这个特性,让两个字符做减法运算就能得到一个int类型的值,进而推导出让一个数字字符对'0'做减法,就能到该字符对应的那个整数,比如'5'减去'0'等于5。

又由于一个整数有低位和高位的概念,比如个位、十位、百位、千位等,而任意整数都会满足如下规律:

个位就是个位上的数字乘以10的0次幂,十位就是十位上的数字乘以10的1次幂,百位就是百位上的数字乘以10的2次幂,千位就是千位上的数字乘以10的3次幂,以此类推

最后将上面运算的结果累加起来,就是最终的整数,比如 3256=3*1000+2*100+5*10+6。

 

【代码实现】

    /**
     * 自己实现字符串转整数
     * 基本思路: 字符串 -> 字符 -> 整数
     * 整数拆分规律: 3256 = 3*10^3 + 2*10^2 + 5*10^1 + 6*10^0
     * @param s
     * @return
     */
    public static int parseInt(String s) {
        //保留原始参数
        String str = s;
        if (str == null || str == "") throw new NumberFormatException("For input string:\"" + s + "\"");
        //是否为负数
        boolean negative = false;
        // 是否以+号或-号开头
        if(str.startsWith("+") || str.startsWith("-")) {
            if (str.startsWith("-")) negative = true;
            str = str.substring(1);
            // 以+或-开头,但是后面没有数字
            if (str == "" || str.length() == 0) throw new NumberFormatException("For input string:\"" + s + "\"");
        }
        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:\"" + s + "\"");
            // 先根据字符之间进行运算来得到int值,再根据每个数字所在的位数来计算应该乘10的几次幂(Math.pow()函数用于求幂),最后累加。
            result += (chars[i] - '0') * Math.pow(10, chars.length - i - 1);
            // 是否超出int的最小值
            if (negative && -result < Integer.MIN_VALUE) {
                throw new NumberFormatException("For input string:\"" + s + "\"");
            }
            // 是否超出int的最大值
            if (!negative && result > Integer.MAX_VALUE) {
                throw new NumberFormatException("For input string:\"" + s + "\"");
            }
        }
        if (negative) result = -result;
        return (int) result;
    }

 

我怎么感觉我的代码实现要比JDK官方的更简洁更易懂呢^_^

 

posted @ 2017-12-27 00:24  xuebusi  阅读(308)  评论(0编辑  收藏  举报