8.String to Integer (atoi)

    private static final int maxDiv10 = Integer.MAX_VALUE / 10;
    public int myAtoi(String str) {
        int len = str.length();
        int sign = 1;//符号位
        int num = 0;
        int i = 0;
        while(i < len && Character.isWhitespace(str.charAt(i))) ++i;//去掉前面空字符
        if(i<len &&str.charAt(i)=='+'){ //-negative number
            sign = 1;
            ++i;
        }else if(i < len && str.charAt(i) == '-') { //+postive number
            sign = -1;
            ++i;
        }
        while(i<len && Character.isDigit(str.charAt(i))){
            int digit = Character.getNumericValue(str.charAt(i));
            if(num > maxDiv10 || (num == maxDiv10 && digit >= 8)) {//2147483647  -2147483648
                return (sign == -1)? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            num = num * 10 + digit;
            ++i;
        }
        return sign * num;
    }

猜你喜欢

转载自blog.csdn.net/STU756/article/details/81677189
今日推荐