Code working fine on my ide but giving Runtime Error here. Can someone please point out the problem?


  • 0
    C
    class Solution {
    public:
           int atoi(const char *str) {
                int count(0);
                int ans(0);
                const char *tmp = str;
                if(!(*tmp))
                   return 0;
                while(*tmp == '-' || *tmp == '+' || *tmp == ' ')
                {
                     tmp++;
                }
                while(*tmp != '\0')
                {
                     count++;
                     if((int)*tmp < 48 || (int)*tmp >57)
                     {
                        return 0;
                     }
                     tmp++;
                }
                tmp = str;
                while(*tmp == '-' || *tmp == '+' || *tmp == ' ')
                {
                    tmp++;
                }
               cout << ans << endl;
               while(count)
               {
                    ans += ((int)(*tmp)-48) * (int)pow(10.0,(double)--count);
                    cout << ans << endl;
                    if(ans <= INT_MIN)
                    {
                         return INT_MIN;
                    }
                    if(ans >= INT_MAX)
                    {
                         return INT_MAX;
                    }
                    tmp++;
                }
                if(*str == '-')
                   return -ans;
               else
                   return ans;
       }
    

    };

    This code fails for the input "+1" here but when I run the same code on my IDE, it works just fine. I am not able to figure out the problem with this code. Can anyone please help me?


  • 0
    S

    Maybe here is the problem.

    cout << ans << endl;
    

    Do not cout anything, or it will lead to unexpected judgement.


  • 0
    C

    Thanks for your response Shangrila. It worked on "+1" but now I am getting a runtime error on input "-1". I ran this code on my IDE with the same input and I get the right answer. I don't understand what is wrong here.

    Thanks again for taking the time to respond.


Log in to reply
 

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