LeetCode8. String to Integer (atoi)

Posted 医生工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode8. 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;
    }
};

 

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