Java Clean Code 340ms


  • 0
    C
    public int myAtoi(String str) {
            return atoi(trim(str));
        }
        
        private String trim(String str) {
            StringBuilder sb = new StringBuilder();
            boolean foundDigit = false;
        
            for (char c : str.toCharArray()) {
                if (foundDigit) {
                    if (!Character.isDigit(c)) {
                        break;
                    } else {
                        sb.append(c);
                    }
                }
                if (!foundDigit && !Character.isWhitespace(c)) {
                    if (Character.isDigit(c) || c == '-' || c == '+') {
                        sb.append(c);
                        foundDigit = true;
                    } else {
                        break;
                    }
                }
            }
            return sb.toString();
        }
    
        private int atoi(String string) {
            long sum = 0;
            boolean negative = false;
            int zeroes = string.length() - 1;
            for (char c : string.toCharArray()) {
                if (c == '-') {
                    negative = true;
                } else if (c == '+') {
                    negative = false;
                } else {
                    sum += Character.getNumericValue(c) * Math.pow(10, zeroes);
                }
                zeroes--;
            }
        
            sum = negative ? -sum : sum;
            if (sum > Integer.MAX_VALUE) {
                sum = Integer.MAX_VALUE;
            }
            if (sum < Integer.MIN_VALUE) {
                sum = Integer.MIN_VALUE;
            }
            return (int) sum;
        }

Log in to reply
 

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