AC JAVA solution, easy to read


  • 0
    M
    public int myAtoi(String str) {
            // null or zero length string
            if (str == null || str.length() == 0) return 0;
            // delete all whitespace.
            str = str.trim();
            // get the sign
            boolean sign = true;
            if (str.charAt(0) == '+' || str.charAt(0) == '-') sign = str.charAt(0) == '+' ? true : false;
            else if (str.charAt(0) - '0' < 0 || str.charAt(0) - '0' > 9) return 0;
            else str = "+" + str;
            // build the number string
            int num_length = 0;
            for (int i = 1; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c - '0' >= 0 && c - '0' <= 9) {
                    num_length++;
                    if (num_length > 10) return sign ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                else break;
            }
            // get the range
            if (num_length == 0) return 0;
            Long num = Long.parseLong(str.substring(1, num_length+1));
            if (!sign) num = -num;
            if (num >= Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (num <= Integer.MIN_VALUE) return Integer.MIN_VALUE;
            return sign ? Integer.parseInt(str.substring(1, num_length+1)) : -Integer.parseInt(str.substring(1, num_length+1));
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.