8.String to Integer (atoi)

Posted smallredness

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了8.String to Integer (atoi)相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int myAtoi(string str) {
        if (str.empty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.size();
        while (i < n && str[i] == ' ') ++i;
        if (i < n && (str[i] == '+' || str[i] == '-')) {
            sign = (str[i++] == '+') ? 1 : -1;
        }
        while (i < n && str[i] >= '0' && str[i] <= '9') {
            if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
                return (sign == 1) ? INT_MAX : INT_MIN;
            }
            base = 10 * base + (str[i++] - '0');
        }
        return base * sign;
    }
};

以上是关于8.String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章

8. String to Integer (atoi)

8. 字符串转整数(实现atoi函数) [leetcode 8: String to Integer (atoi)]

8. 字符串转整数(实现atoi函数) [leetcode 8: String to Integer (atoi)]

8. String to Integer (atoi)

8. String to Integer (atoi)

8. String to Integer (atoi)