8. 字符串转整数 (atoi)

class Solution {
    public int myAtoi(String str) {
        str = str.trim();

        if (str.length() == 0 || str == null) {
            return 0;
        }

        char[] cs = str.toCharArray();
        boolean b = false;

        if (cs[0] == '-') {
            b = true;
        } else {
            if (cs[0] != '+' && (cs[0] < '0' || cs[0] > '9')) {
                return 0;
            }
        }

        str = cs[0] + "";

        for (int i = 1; i < cs.length; i++) {
            if (cs[i] < '0' || cs[i] > '9') {
                break;
            }

            str += cs[i];
        }

        if (str.length() == 1 && (str.charAt(0) == '-' || str.charAt(0) == '+')) {
            return 0;
        }

        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            if (b) {
                return Integer.MIN_VALUE;
            } else {
                return Integer.MAX_VALUE;
            }
        }
    }
}
image.png

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