2014年11月29日星期六

[Leetcode] String to Integer (atoi)

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

First, we trim the leading and tailing spaces. Then, we read the first character to see if it is '-' or '+' to determine the sign. After that, we check each character, if it is not valid, we return the current result, other wise, we check to see if it would overflow or not. In my implementation, I check if it would overflow separately.


    public int atoi(String str) {
        str = str.trim(); // handle spaces
        if(str.length() == 0)
            return 0;
        int res = 0;
        if(str.charAt(0) == '-') { // negative integer
            str = str.substring(1);
            for(int i = 0; i < str.length(); i++) {
                if(str.charAt(i) < '0' || str.charAt(i) > '9') // invalid character
                    break;
                int num = str.charAt(i) - '0';
                if((Integer.MIN_VALUE + num) / 10 > res) // overflow
                    return Integer.MIN_VALUE;
                else
                    res = res * 10 - num;
            }
        }
        else {
            if(str.charAt(0) == '+')
                str = str.substring(1);
            for(int i = 0; i < str.length(); i++) {
                if(str.charAt(i) < '0' || str.charAt(i) > '9') // invalid character
                    break;
                int num = str.charAt(i) - '0';
                if((Integer.MAX_VALUE - num) / 10 < res) // overflow
                    return Integer.MAX_VALUE;
                else
                    res = res * 10 + num;
            }
        }
        return res;
    }

没有评论:

发表评论