40ms beat 80.85% JAVA.


  • 0
    C
    if ("".equals(str) || str == null) {
                return 0;
            }
            int res = 0;
            int i = 0, sign = 1;
    
            str = str.trim();
            if (str.startsWith("-")) {
                i = 1;
                sign = -1;
            } else if(str.startsWith("+")) {
                i = 1;
            }
    
            int after = res;
            for (; i < str.length(); i++) {
                int minus = str.charAt(i) - '0';
                if (minus < 0 || minus > 9) {
                    break;
                }
                after = res * 10 + minus;
                if(after / 10 != res) {
                    break;
                }
                res = after;
            }
    
            res = sign * res;
            if (res != after * sign) {
                return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
    
            return res;
    

Log in to reply
 

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