Java solution which beats 95%


  • 0
    C
    class Solution {
        public int myAtoi(String str) {
            if (str == null) return 0;
            
            boolean negative = false;
            boolean leadingSpacePossible = true;
            
            long result = 0;
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (Character.isDigit(c)) {
                    leadingSpacePossible = false;
                    result = result*10 + (c - '0');
                    if (result > Integer.MAX_VALUE) {
                        if (negative) return Integer.MIN_VALUE;
                        else return Integer.MAX_VALUE;
                    }
                } else if (leadingSpacePossible && c == '-') {
                    negative = true;
                    leadingSpacePossible = false;
                } else if (leadingSpacePossible && c == '+') {
                    leadingSpacePossible = false;
                } else if (result > 0) {
                    break;  // reach the first non-digit char
                } else if (leadingSpacePossible && c == ' ') {
                    // do nothing, filter out leading space
                } else
                    return 0;  // non-digit before digit
            }
            
            if (negative) 
                return (int)-result;
            else
                return (int)result;
        }
    }
    

Log in to reply
 

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