[LeetCode] String to Integer (atoi)

Implementatoito 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.

Update (2015-02-10):
The signature of theC++function had been updated. If you still see your function signature accepts aconst char *argument, please click the reload buttonto reset your code definition.

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.

实现atoi函数:将一个字符串转换为整数。

这里没有给定输入的格式,所以需要对输入的字符串进行一系列判断处理:

1. 处理字符串开头的多余空格(整数字符前的空格)。

2. 处理字符串的符号字符(正负号)。

3. 处理整数字符串后面的额外字符(忽略不处理)

4. 处理字符串为空或无效(字符串为空或不存在整数字符)

5. 溢出检测(超过最大/最小值,返回其最大/最小值)。

class Solution {
public:
    int myAtoi(string str) {
        unordered_set<char> s({'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'});
        // judge empty.
        if (str.empty())
            return 0;
        int i = 0, n = str.size(), cur = 0;
        // discard whitespace characters.
        for (char c : str) {
            if (c != ' ')
                break;
            else
                i++;
        }
        // deal sign before int number.
        int sign = 1;
        if (str[i] == '-') {
            sign = -1;
            i++;
        } 
        else if (str[i] == '+') {
            i++;
        } 
        // traversal the number in str.
        int t = n - i;
        while (t--) {
            // just deal the number if other non-number characters after the int number. 
            if (s.count(str[i])) {
                int c = str[i] - '0';
                // deal out of ranges of representable values.
                if (sign > 0 && (cur > INT_MAX / 10 || (cur == INT_MAX / 10 && c > INT_MAX % 10))) {
                    cur = INT_MAX;
                    break;
                }
                else if (sign < 0 && (cur > (unsigned)INT_MIN / 10 || (cur == (unsigned)INT_MIN / 10 && c > (unsigned)INT_MIN % 10))) {
                    cur = INT_MIN;
                    break;
                }
                cur = cur * 10 + c;
                i++;
            }
            else
                break;
        }
        return sign * cur;
    }
};
// 22 ms

相关推荐