【LeetCode】8. 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.

提示:

此题的难点在于各种特殊情况的处理:

  • 忽略开头的空白字符;
  • 忽略第一串连续数字后的所有非法字符;
  • 注意正负号的处理;
  • 如果数字的大小超出了int的范围,则根据其正负,返回 INT_MAX (2147483647) 或 INT_MIN (-2147483648)。

代码:

class Solution {
public:
    int myAtoi(string str) {
        long result = 0;
        int indicator = 1;
        for (int i = 0; i<str.size();)
        {
            i = str.find_first_not_of(' ');
            if (str[i] == '-' || str[i] == '+')
                indicator = (str[i++] == '-') ? -1 : 1;
            while (isdigit(str[i]))
            {
                result = result * 10 + (str[i++] - '0');
                if (result*indicator >= INT_MAX) return INT_MAX;
                if (result*indicator <= INT_MIN) return INT_MIN;
            }
            return result*indicator;
        }
    }
};
原文地址:https://www.cnblogs.com/jdneo/p/4754214.html