Java O(n) time, O(1) space all handled test cases


#1
public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public int atoi(String s) {
    // Handling spaces
    s = s.trim();
    long ans = 0;
    int i=0;
    // Handling sign
    int val = s.charAt(i) - '0';
    int sign = 1;
    if(val == '-' - '0') {
        sign = -1;
        i++;
    }    
    if(val == '+' - '0') {
        sign = 1;
        i++;
    }    
    
    
    for(; i<s.length(); i++) {
        val = s.charAt(i) - '0';
        if(val < 0 || val > 9)
            break;
        // If 1st ele is int
        if(i == 0)
            ans += val;
        else
            ans = ans * 10 + val;
        // If int overflows 
        if(ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) {
            if(sign == 1)
                return Integer.MAX_VALUE;
            if(sign == -1)
                return Integer.MIN_VALUE;
        }        
    }
    return sign * (int)ans;
}

}