Right locally, wrong here. Please help me to look at it .


  • 1
    S

    Here is the error I receive,

    Input: " 010"
    Output: 0
    Expected: 10

    Here is my code,

    #include<iostream>
     int atoi(const std::string &str){
            unsigned int index=0;
            while(str[index]!='+'&&str[index]!='-'&&str[index]<='0'&&str[index]>'9')
                ++index;
            bool sign=str[index]=='-'?false:true;
            index=str[index]=='-'||str[index]=='+'?index+1:index;
            int result=0;
            for(;index<str.size();++index){
                if(str[index]<'0'||str[index]>'9') return 0;
                if(sign&&(INT_MAX/10<result||(INT_MAX/10==result&&str[index]-48>7))) 
                    return INT_MAX;
                if(!sign&&(INT_MAX/10<result||(INT_MAX/10==result&&str[index]-48>8))) 
                   return INT_MIN;
                result=result*10+str[index]-48;
            }
            return sign?result:result*-1;
        }
        
    int main(){
        std::cout<<atoi("    010")<<std::endl;
        return 0;
    }
    

    This is a very simple test case, it returns 10 on my local mac. Could anyone please tell me why?


  • 0
    A

    I guess it is because your main function called the c++ built-in atoi rather than yours. You should change then name of your atoi.


Log in to reply
 

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