凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 8. String to Integer (atoi)

分类:algorithm| 发布时间:2016-06-27 23:58:00


题目

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.

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

题意

将一个字符串表示的数字转化为 integer。

解法

这道题也相当简单,就是需要注意要跳过前面的空格,以及处理数字开头的 '+' 以及 '-' 号。 同时还要处理结果溢出是返回类型的最大值或最小值。

class Solution {
public:
    int myAtoi(string str) {
        int sign = 1;
        int end = str.size() - 1, beg = 0;
        // skip space
        for (; beg <= end; ++beg) {
            if (str[beg] != ' ') {
                break;
            }
        }

        if (str[beg] == '-') {
            sign = -1;
            beg += 1;
        } else if (str[beg] == '+') {
            sign = 1;
            beg += 1;
        }

        long ret = 0;
        char c;
        for (; end >= beg; ++beg) {
            c = str[beg];
            if (c < '0' || c > '9') {
                return ret * sign;
            }

            ret *= 10;
            ret += (c - '0');
            if (ret * sign > INT_MAX) {
                return INT_MAX;
            } else if (ret * sign < INT_MIN) {
                return INT_MIN;
            }
        }
        return ret * sign;
    }
};