Atoi simple implementation


#1
int Solution::atoi(const string A) {
int sign=1;
long int num=0;
int i=0;
while(A[i]==' ') i++;

if(A[i]=='+'){
    i++;
}

if(A[i]=='-'){
    sign=-1;
    i++;
}

while(A[i]!=' '&&isdigit(A[i]))
{   
    num = 10 * num + A[i]-'0';
    if(num*sign >= INT_MAX)
        return INT_MAX;
    else if(num*sign<=INT_MIN)
        return INT_MIN;
    i++;
}
return num*sign;

}


#2

you haven’t considered the case where string is like “+123”.


#3

dont confuse others by uploading wrong code


#4

The code is almost correct. Only two modifications are needed. Firstly, the obvious one is to take out the following part from the last while loop as this will terminate the program after one iteration of while loop:

if(num*sign >= INT_MAX)
        return INT_MAX;
    else if(num*sign<=INT_MIN)
        return INT_MIN;

The second correction is to keep a count of the number of times the last while loop is entered. If it is entered more than 10 times (which is the maximum size an int type variable can be), you know that you have to output INT_MAX or INT_MIN. The correct code is as follows:

int Solution::atoi(const string A) 
{
    int sign=1;
    long int num=0;
    int i=0;
    while(A[i]==' ') i++;
    if(A[i]=='+') i++;
    if(A[i]=='-')
    {    
        sign=-1;
        i++;
    }
    int count=0;
    while(A[i]!=' ' && isdigit(A[i]) && count<11)
    {   
        num = 10 * num + A[i]-'0';
        i++;
        count++;
    }
    if(num*sign >= INT_MAX) return INT_MAX;
    else if(num*sign<=INT_MIN) return INT_MIN;
    return num*sign;
}