simple Java solution


  • 0
    F
    int myAtoi(String str) {
            if (str == null || str.isEmpty()) {
                return 0;
            }
            str = str.trim();
            int sign = 1, result = 0, i = 0;
            if (str.charAt(0) == '-') {
                i++;
                sign = -1;
            } else if (str.charAt(0) == '+') {
                i++;
                sign = 1;
            }
            char zero = '0', nine = '9';
            for (; i < str.length() && zero <= str.charAt(i) && str.charAt(i) <= nine; i++) {
                if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > Integer.MAX_VALUE % 10)) {
                    return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                result = result * 10 + (str.charAt(i) - zero);
            }
    
            return sign * result;
        }
    

Log in to reply
 

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