My Simple Java solution


  • 1
    H
    public int myAtoi(String str) {
        if (str.length() == 0) return 0;
        int idx = 0;
        while (str.charAt(idx) == ' ' || str.charAt(idx) == '0') idx++;
        if (idx > 0)
            return myAtoi(str.substring(idx, str.length()));
        Long res = 0L;
        boolean flag = false;
        boolean isNegative = false;
        if (str.charAt(0) == '-' || str.charAt(0) == '+') flag = true;
        for (char ch : str.toCharArray()) {
            if (flag) {
                flag = false;
                isNegative = str.charAt(0) == '-';
                continue;
            }
            if (ch < '0' || ch > '9') return res.intValue();
            int elem = isNegative ? -(ch - '0') : ch - '0';
            res = res * 10 + elem;
            if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            else if (res < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        }
        return res.intValue();
    }
    

    I use a simple Long result to handle 32-bit int overflow.


Log in to reply
 

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