Monday, June 2, 2014

Leetcode atoi

5 conditions need to check
1. null or empty string
2. skip all the white spaces
3. negative and positive sign
4. calculate the value
5. handle the overflow : here we used double type to avoid overflow. It make the code much clear.

    public int atoi(String str) {
        //null or empty string
        if (str == null || str.length() == 0) {
            return 0;
        }
        //skip all the white space
        double result = 0;
        boolean isNegative = false;
        int index = 0;
        while (index < str.length() && str.charAt(index) == ' ') {
            index++;
        }
        //negative and positive sign
        if (str.charAt(index) == '+') {
            isNegative = false;
            index++;
        } else if (str.charAt(index) == '-') {
            isNegative = true;
            index++;
        }
        //calculate the value
        while (index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9') {
            result = result*10 + (str.charAt(index) - '0');
            index++;
        }
        if (isNegative) {
            result = result * (-1);
        }
        //handle the overflow
        if (result > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (result < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return (int)result;
    }

No comments:

Post a Comment