字符串转整数

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

样式:输入"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;
    }

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容