Leetcode-8: String to Integer

这道题的题目出的比较含糊,测试例子里面的情况都要特别注意。我的code写的太冗余,注释掉的code是Leetcode里面的,写的比较好。

#include 
#include 
#include 

using namespace std;

int myAtoi(string str) {
    if (str.size()==0) return 0;   //empty string returns 0

    size_t flagPos=str.size();
    size_t startPos=str.size();
    for (auto i=0; iif ((str.at(i)=='+' || str.at(i)=='-') && flagPos==str.size() )flagPos=i;

        if (isdigit(str.at(i))) {
            startPos=i;
            break;
        }
    }
    if (flagPos!=str.size() && (startPos-flagPos>1)) return 0;
    if (startPos==str.size()) return 0;   //invalid string returns 0
    else if (startPos>=1 && str.at(startPos-1)!='+' && str.at(startPos-1)!='-' && str.at(startPos-1)!=' ') return 0;

    bool positive=true;
    if ((startPos>0) && (str.at(startPos-1)=='-')) positive=false;
    if (positive && startPos>=2 && str.at(startPos-2)=='-') return 0;
    if (!positive && startPos>=2 && str.at(startPos-2)=='+') return 0;

    int result=positive? str.at(startPos)-'0' : '0' - str.at(startPos);
    for (auto i=startPos+1; iif (isdigit(str.at(i))) {
            if (!positive) {
                if (result < INT_MIN / 10 || (result == INT_MIN / 10 && str.at(i) - '0' > 7))
                    return INT_MIN;
                else
                    result=result*10+'0'-str.at(i);
            }
            else {
                if (result >  INT_MAX / 10 || (result == INT_MAX / 10 && str.at(i) - '0' > 7))
                    return INT_MAX;
                else
                    result=result*10+str.at(i)-'0';
            }
         }
         else
            break;
    }

    return result;
}
#if 0
int myAtoi(string str) {
    int sign = 1, base = 0, i = 0;
    while (str[i] == ' ') { i++; }
    if (str[i] == '-' || str[i] == '+') {
        sign = 1 - 2 * (str[i++] == '-');
    }
    while (str[i] >= '0' && str[i] <= '9') {
        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
            if (sign == 1) return INT_MAX;
            else return INT_MIN;
        }
        base  = 10 * base + (str[i++] - '0');
    }
    return base * sign;
}
#endif // 0

int main()
{
    string s="123";
    cout<string s1="-23211";
    cout<string s2="2147483647";
    cout<string s3="-2147483648";
    cout<string s4="000";
    cout<string s5="+-2";
    cout<string s6=" ++1""  -0012a42";
    cout<string s7="2147483648";
    cout<string s8="-2147483649";
    cout<string s9="  +  413";
    cout<string s10=" ++1";
    cout<string s11=" b11228552307";
    cout<string s12="    010";
    cout<string s13="w10734368512";
    cout<return 0;
}

你可能感兴趣的:(Leetcode)