8. 字符串转换整数 (atoi)

104 阅读1分钟

class Solution {
    public int myAtoi(String s) {
        boolean negative = false;//默认为正数
        //扫s
        int i = 0;
        //遇到空格,往后
        while (i < s.length() && s.charAt(i) == ' ') {
            i++;
        }
        if (i == s.length()) {//去掉前导空格以后到了末尾了, “ ”这样的
            return 0;
        }

        //只能有一个+或-号,所以单独写出来
        if (s.charAt(i) == '-') {
            negative= true;
            i++;
        } else if (s.charAt(i) == '+') {
            i++;
        } else if (!Character.isDigit(s.charAt(i))) {
            return 0;
        } 

        int res = 0;
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            if (!negative) {
                if(res > 214748364 || (res == 214748364 && s.charAt(i) - '0' > 7)) {
                    return 2147483647;
                }
            } else {
                if(res > 214748364 || (res == 214748364 && s.charAt(i) - '0' > 8)) {
                    return -2147483648;
                }
            }
            res = res * 10 + (s.charAt(i) - '0');
            i++;
        }
        return negative ? -res : res;
    }
}