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.

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.

spoilers alert... click to show requirements for atoi.

Subscribe to see which companies asked this question

 
class Solution {
public:
    /*
     * 这个问题需要考虑很多边界情况
     * 1.如果str为空,返回空
     * 2.如果str前面有空格,过滤掉空格
     * 3.如果str > INT_MAX ,返回 INT_MAX
     * 4.如果str < INT_MIN, 返回 INT_MIN
     * 5.如果str格式不匹配,返回已经匹配成功的部分
     */
    int myAtoi(string str) {
        int begin = 0;
        int end = str.length() - 1;
        //过滤掉左右的空格
        while (str[begin] == ' ') {
            begin++;
        }

        while (str[end] == ' ') {
            end--;
        }

        //设置负号
        bool minus = false;
        if ('-' == str[begin]) {
            minus = true;
            begin++;
        } else if ('+' == str[begin]) {
            minus = false;
            begin++;
        }

        double res = 0;
        for (begin; begin<=end; begin++) {
            if (str[begin] >= '0' && str[begin] <= '9') {
                res = res * 10 + str[begin] - '0';
            } else {
                break;
            }
        }

        if (!minus) {
            if (res > INT_MAX) {
                res = INT_MAX;
            }
        } else {
            res = res * -1;
            if (res < INT_MIN) {
                res = INT_MIN;
            }
        }

        return (int)res;
    }
};
原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5097125.html