Java Solution:Use Regex and Exception


  • 0
    9
            int result, sign = 1;
            if (str.matches("\\s*[+-]?\\d+.*")) {
                java.util.regex.Matcher m = java.util.regex.Pattern.compile("[+-]?\\d+").matcher(str);
                String s = str;
                if (m.find()) s = m.group();
                if (s.charAt(0) == '+' || s.charAt(0) == '-') {
                    sign = s.charAt(0) == '-' ? -1 : 1;
                    s = s.substring(1);
                }
                try {
                    result = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
            } else {
                return 0;
            }
            return sign * result;

Log in to reply
 

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