Java 37ms using regular expression and the code needs to be optimized


  • -1
    F
    public int myAtoi(String str) {
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        Pattern pattern = Pattern.compile("^([+-]?)0*(\\d*)");
        Matcher matcher = pattern.matcher(str);
        int flag = 1;
        if (matcher.find()) {
            if (matcher.group(1).equals("-")) {
                flag = -1;
            }
            String num = matcher.group(2);
            if (num.length() == 0) {
                return 0;
            }
            if (num.length() >= 10) {
                long tmp = Long.parseLong(num.substring(0, Math.min(11, num.length())));
                tmp *= flag;
                if (tmp < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
                if (tmp > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
                return (int) tmp;
            } else {
                return flag * Integer.parseInt(num);
            }
        }
        return 0;
    }

Log in to reply
 

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