Step by Step commented solution


#1
int Solution::atoi(const string A) 
{
    int i=0, sign=1, base=0;
    //skip all the inital white spaces
    while(A[i] == ' ')
        i++;
    
    //check the sign of the number;
    if(A[i] == '-' || A[i] == '+')
        sign = 1 - 2*(A[i++] == '-');
    
    //check for numerical characters
    while(A[i] >= '0' && A[i] <= '9')
    {
        // check for overflow
        if(base > INT_MAX/10 || (base == INT_MAX/10 && A[i] - '0' > 7))
        {
            if(sign == 1)
                return INT_MAX;
            else
                return INT_MIN;
        }
        base = base*10 + (A[i++] - '0'); // Append the numbers by incrementing  the position
    }
    return base*sign;
        
}