C++ code crashing on " 010"


  • 1
    I

    Hi I can not find a bug in my code:

    int atoi(string str) {
            if(str.empty()){
                return 0;
            }
            int first = 0;
            while((first < str.size()) && (str[first]==' ')){
                first++;
            }
            bool negative = false;
            if(str[first] =='-'){
                negative = true;
            }
            if( (str[first] =='+')||(str[first] =='-')){
                first++;
            }
            long result = 0;
            while(( (str[first-'0'] < 0)||(str[first-'0'] > 9)) && (first<str.size())){
                result = result *10 + str[first]-'0';
                first++;
                if(result <0){
                    return 0;
                }
                if( result > 2147483647){
                    return INT_MAX;
                }
                if((result > 2147483648)&&(negative)){
                    return INT_MIN;
                }
            }
            if(negative){
                result = -1*result;
            }
            return result;
        }
    

    It is crashing on input string " 010"(the space should be there 4 times but I guess this is just a detail) - I run it on my PC- there it works without any problem giving output 10 as expected but during the online submission the result is 0.
    Does anyone have a guess what can cause this problem?


Log in to reply
 

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