C++ Beautiful Solution 0(n) Dry run to understand 100% faster on leetcode


#1
indent preformatted text by 4 spaces
int Solution::atoi(const string s) {
    long ans=0,mul=1;
    int sign=1;
    bool start=false;
    for(auto c:s){
        if('0'<=c&&c<='9'){
            ans=ans*10+(c-'0');
            start=true;
            if(ans>INT_MAX)
                break;
        }
        else if(!start&&c==' ')
            continue;
        else if(!start&&c=='+'){
            start=true;
        }
        else if(!start&&c=='-'){
            start=true;
            sign=-1;
        }
        else{
            break;
        }
    }
    ans*=sign;
    if(ans>INT_MAX){
        return INT_MAX;
    }
    else if(ans<INT_MIN)
        return INT_MIN;
    return (int) ans;

}


#2

Lovely solution mate! Thanks for sharing.


#3

what exactly is the function of the “start” boolean variable here?