String to Integer (atoi)


Implement function atoi to convert a string to an integer.

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.

https://leetcode.com/problems/string-to-integer-atoi/

Discussion


  1. 怎么定位到第一个正负号或者数字
  2. 怎么判断溢出。直接跟INT_MAX是肯定不行的,都溢出了还怎么比啊。。。正确做法是当前结果大于INT_MAX/10的时候,再有数字进来就溢出了,或者当前结果等于INT_MAX/10, 再进来的数字比7大的时候也溢出了。
  3. 将一个char转成int的方法是减去48或者'0'

Solution


class Solution {
public:
    int myAtoi(string str) {
        if (str.empty()) {
            return 0;
        }

        int ans = 0;
        int sign = 1;
        int i = 0;

        // Skip ' '.
        while (str[i] == ' ') {
            ++i;
        }

        // Parse sign.
        if (str[i] == '+') {
            ++i;
        } else if (str[i] == '-') {
            sign = -1;
            ++i;
        }

        // Compute integer.
        for (; i < str.length() && isdigit(str[i]); ++i) {
            if(ans > INT_MAX/10 || (ans == INT_MAX/10 && (str[i] - '0') > INT_MAX % 10)) { //判断溢出
                return sign==1? INT_MAX: INT_MIN;
            }
            ans *= 10;
            ans += str[i] - '0';
        }

        ans *= sign;
        return ans;

    }
};

判断溢出的时候不用判断sign为负最后一位为8的情况了,这时候虽然没有溢出,但刚刚好是INT_MIN。

results matching ""

    No results matching ""