Share my c++ code with explanation(easy to understand)


  • 1
    J
    int atoi(string str) {
        bool isValid=false,isNegative=false;
        double res=0;
        for(string::iterator i=str.begin();i!=str.end();++i){
            if(*i==' ')continue;
            //check if there is at lesat one number after the sign
            if((*i=='+'||*i=='-')&&i+1!=str.end()&&isdigit(*(i+1))){
                if(*i=='-')isNegative=true;
                i++;
            }
            if(isdigit(*i))isValid=true;
            while(isValid&&i != str.end() && isdigit(*i)){
                res=res*10+(*i-'0');
                i++;
            }
            break;
        }
        if(isNegative)res=0-res;
        if(res>INT_MAX)return INT_MAX;
        if(res<INT_MIN)return INT_MIN;
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.