8ms c++ solution


  • 5
    W
        long int res = 0;
        int size = str.size();
        int i, flag;
        
        i=0;flag = 1;
        i = str.find_first_not_of(' ');
        if(str[i]=='-'){
            flag = -1;
            i++;
        }
        else if(str[i]=='+'){
            i++;
        }
        for(; isdigit(str[i])&&res<=INT_MAX&&i<size; i++)
            res = res*10+(int)(str[i]-'0');
        if(flag*res>INT_MAX)
            return  INT_MAX;
        if(flag*res< INT_MIN)
            return  INT_MIN;
        return flag*res;

  • 1
    G

    You're taking advantage of using long int as result. If res is int, your overflow detection would not work.


Log in to reply
 

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