leetcode-8-string to integer(atoi)

Problem Description:

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.

题目大意:

实现一个字符串向整数转换的函数。

Solutions:

首先,第一步是去掉首位空格;
然后,验证第一个字符是否是+或者-或者数字,如果都不是,则返回0;
再做简单的处理即可,注意超过INT范围的情况,所以临时变量建议用long long int;

Code in C++:

class Solution {
public:
    int myAtoi(string str) {
        int i = 0;
        bool isN = false;
        long long int tem=0;
        for(;i<str.size();i++)
            if(str[i]!=' ') break;
        if(!isdigit(str[i])&&str[i]!='+'&&str[i]!='-') return 0;
        if(str[i]=='-') {i++;isN = true;}
        else if(str[i]=='+') i++;
        for(;i<str.size();i++){
            if(isdigit(str[i])){
                tem=tem*10+(str[i]-'0');
                if(tem>INT_MAX) return isN?INT_MIN:INT_MAX;
            }
            else break;
        }
        return isN?-(int)tem:(int)tem;


    }
};