4ms Java Simple solution


  • 0
    N

    public int myAtoi(String str) {
        if(str.length() == 0) return 0;
        int ans = 0,i=0,sign=1,digit10=Integer.MAX_VALUE/10,digit;
        while(i<str.length()&&str.charAt(i) ==' ') i++;
        if(str.charAt(i)=='-') {i++; sign = -1;}
        else if (str.charAt(i)=='+') {i++;}
        while(i<str.length() && Character.isDigit(str.charAt(i))){
            digit = Character.getNumericValue(str.charAt(i));
            if(ans>digit10) return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            if(ans==digit10 && digit>=8 && sign == -1) return Integer.MIN_VALUE;
            if(ans==digit10 && digit>=7 && sign == 1) return Integer.MAX_VALUE;
            ans = ans*10 + digit;
            i++;
        }
        return sign*ans;
    }
    

Log in to reply
 

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