LeetCode 算法学习(5)

题目描述

String to Integer (atoi)
Implement atoi which converts a string to an integer.

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.

Note:

Only the space character ’ ’ is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

题目大意

字符串转整数,当出现溢出时返回INT_MAX(上溢)或INT_MIN(下溢)。

思路分析

遍历字符串与判断是否合法,主要考虑上界和下界,与上一篇思路基本一致。

关键代码

    int myAtoi(string str) {
        int n = str.length();
        int result = 0;
        bool begin = false;
        bool sign = true;
        for (int i = 0; i < n; i++) {
            if (str[i] >= '0' && str[i] <= '9') {
                begin = true;
                int pop = str[i]-'0';
                if (result > INT_MAX/10 ||(result == INT_MAX/10 && pop > 7)) return INT_MAX;
                if (result < INT_MIN/10 ||(result == INT_MIN/10 && pop > 8)) return INT_MIN;
                if (!sign) {
                    pop = 0-pop;
                }
                result = result*10+pop;
            } else if (begin == true) {
                break;
            } else if (str[i] == ' ') {
                continue;
            } else if (str[i] == '-') {
                begin = true;
                sign = false;
            } else if (str[i] == '+') {
                begin = true;
                sign = true;
            } else {
                break;
            }
        }
        return result;
    }

总结

这题比较简单,需要注意判断的优先级以及标志的设置。

猜你喜欢

转载自blog.csdn.net/L_Realoo/article/details/85266891
今日推荐