[C++][Atoi] code with comments about corner cases to be taken care of


#1
int Solution::atoi(const string A) {
    long val = 0, st=0;
    bool negative = false, seqStarted = false;
    while(st<A.length() && A[st] == ' ') st ++; // skip initial space characters
    for(; st < A.length(); st++) {
        if(A[st] == '-' || A[st] == '+'){    // set the sign and start sequence
            negative = A[st] == '-' ? true : false;
            seqStarted = true;
        }
        else if(A[st]>='0' && A[st]<='9') { // generate the Number
            if(!seqStarted) seqStarted = true;  // start sequence if not already started
            val = val*10 + (A[st]-'0');
            if(negative && (-1*val) < INT_MIN)  return INT_MIN; // check for min bound
            else if(val > INT_MAX)              return INT_MAX; // check for max bound
        }
        else if(!seqStarted)    return 0;   // alpha before Numeric
        else if(seqStarted)     break;  // alpha after Numeric
    }
    return negative ? -1*val : val;
}

Putting some corner cases which are handled with above code:

no numeric, only alpha : "    abcd","    -abcd","    +abcd"
space before numeric : "    -1234","    +1234"
space b/w sign and numeric : "    -  1234"
multiple signs before numeric : "    -+1234"
alpha before numeric : "-abcd1234"
alphanumeric : "  +12ab34 "
overflow/underflow : "27917469321473165","-8932479325697233298"