美文网首页
算法-String转int

算法-String转int

作者: zzq_nene | 来源:发表于2020-07-28 00:04 被阅读0次

    在实现String转int的时候,需要考虑字符串中是否有字符是非数字字符,第一个字符是否是符号字符,比如负号或者正号等。
    数字字符的范围是48-57,即0-9
    而负号字符的ASCII码的值为45

        public static int strToInt(String str) {
            if (str == null || str.length() == 0) {
                return 0;
            }
            int result = 0;
            char[] chars = str.toCharArray();
            int len = chars.length;
            for (int i = len - 1, j = 0; i > 0; i--, j++) {
                // 从尾巴开始取字符
                int c = (int)chars[i];
                // 说明字符串中存在非数字字符
                if (c < 48 || c > 57) {
                    return 0;
                } else {
                    // Math.pow返回10的j次幂值
                    result += (c - 48) * Math.pow(10, j);
                }
            }
            // 有可能c是带有符号的,所以需要把第一个字符单独判断
            // 如果第一个字符并不是负号,并且是数字字符,那么就需要按当前数字乘以10的length-1次幂
            int c = (int)chars[0];
            if (c <= 57 && c >= 48) {
                result += (c - 48) * Math.pow(10, len - 1);
            }
            if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
                return 0;
            } else if (str.equals("2147483648")) {
                // 其实这里2147483648已经是大于int的最大值
                if (c == 45) {
                    result = -2147483648;
                }
            } else if (str.equals("-2147483648")) {
                result = -2147483648;
            } else {
                if (c == 45) {
                    result = -result;
                }
            }
            return result;
        }
    

    相关文章

      网友评论

          本文标题:算法-String转int

          本文链接:https://www.haomeiwen.com/subject/qjrxrktx.html