【LeetCode】8. 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.

虽然是个简单题,但是要考虑的细节挺多的,比如输入空串的话如何输出,输入有+,-号的话怎么办,如果遇到无效输入怎么办?数字溢出了该如何输出?如果遇到的是面试,最好都要弄清楚。

 

class Solution {
public:
    int myAtoi(string str) {
        if (str == "") return 0;
        int flag = 1;
        int res = 0;
        string::const_iterator iter = str.begin(); 

        while (*iter == ' ' && iter != str.end()) iter++;
        
        if (*iter == '+' || *iter == '-'){
            if (*iter == '-') flag = -1;
            *iter++;
        } 

        while (iter!=str.end() && isValidNum(*iter)) {
            int tmp = *iter - '0';
            if (res > (INT_MAX - tmp) / 10 && flag == 1) return INT_MAX;
            if (res > (INT_MAX - tmp) / 10 && flag == -1) return INT_MIN;
            
            res = res * 10 + tmp;
            iter++;
        }
        return flag*res;
    }
    
    bool isValidNum(char c)
    {
        return c >= '0' && c <='9';
    }
};

 

posted on 2016-09-10 10:21  医生工程师  阅读(116)  评论(0编辑  收藏  举报

导航