Simple 3ms Java solution


  • 0

    We can use a variable to store prev result, if prev result not equal to current result division 10, it must be overflow.

    public static int myAtoi(String str) {
    	boolean flag = false;
    	int i = 0;
    	int length = str.length();
        while (i < length && str.charAt(i) == ' ') {
            i++;
        }   
        if (i < length && str.charAt(i) == '+') {
            i++;
        } else if (i < length && str.charAt(i) == '-') {
            flag = true;
            i++;
        }   
        int prevResult = 0;
        int result = 0;
        while (i < length && '0' <= str.charAt(i) && str.charAt(i) <= '9') {
            prevResult = result;
            result = result * 10 + (str.charAt(i) - '0');
            if (prevResult != result / 10) { //overflow
                if (flag) {
                    return Integer.MIN_VALUE;
                } else {
                    return Integer.MAX_VALUE;
                }   
            }   
            i++;
        }   
        if (flag) {
            result = -result;
        }   
        return result;
    }

Log in to reply
 

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