3ms simple Java solution


  • 1
    R
    public int myAtoi(String str) {
        char min = '0';
        char max = '9';
        long out = 0;
        boolean numbersOnly = false;
        boolean sign = false;
        for (int i=0; i<str.length(); i++){
            char x = str.charAt(i);
            if (!numbersOnly){
                if (x == ' ') continue;
                if (x == '+') {
                    sign = true;
                    numbersOnly = true;
                }
                else if (x == '-') {
                    sign = false;
                    numbersOnly = true;
                }
                else if (x >= min && x <= max) {
                    sign = true;
                    numbersOnly = true;
                    i -= 1;
                } 
                else return 0;
            } else {
                if (x < min || x > max) 
                    i = Integer.MAX_VALUE -1;
                else {
                    int num = x - '0';
                    if (x == 0) continue;
                    out *= 10;
                    out += num;
                    if (out > Integer.MAX_VALUE) i = Integer.MAX_VALUE -1;
                }
    
            }
        }
        if (!sign) out *= -1;
        if ( out > Integer.MAX_VALUE ) return Integer.MAX_VALUE;
        else if ( out < Integer.MIN_VALUE ) return Integer.MIN_VALUE;
        else return (int)out;
    }

Log in to reply
 

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