字符串转整数

题目:输入字符串,转变为对应整数

样式:输入"123",输出123

解法:遍历输出

    private static int strToInt(String str) {
        if (str == null) {
            throw new IllegalArgumentException("str == null");
        }
        char[] chars = str.toCharArray();
        boolean sign = true;
        int index = 0;
        if (chars[index] == '-') {
            sign = false;
            index++;
        }
        int result = 0;
        for (; index < chars.length; index++) {
            char num = chars[index];
            if (num == ' ') {
                continue;
            }
            num -= '0';
            if (num > 0 && num < 9) {
                if (sign && (result > Integer.MAX_VALUE / 10 ||
                        (result == Integer.MAX_VALUE / 10 && num > Integer.MAX_VALUE % 10))) {
                    result = Integer.MAX_VALUE;
                    break;
                } else if (!sign && (result - 1 > Integer.MAX_VALUE / 10 ||
                        (result - 1 == Integer.MAX_VALUE / 10 && num > Integer.MAX_VALUE % 10))) {
                    result = Integer.MIN_VALUE;
                    break;
                } else {
                    result = result * 10 + num;
                }
            } else {
                throw new IllegalArgumentException("请输入数字");
            }
        }
        return sign ? result : -result;
    }

主要在于判断正负溢出情况

你可能感兴趣的:(字符串转整数)