C++ easy to understand solution.


  • 0
    C
    int myAtoi(string str) {
        int res = 0;
        unsigned int i = 0;
        bool sign = true;
        while (i < str.size() && isspace(str[i]))
            i++;
        if (i < str.size() && (str[i] == '+' || str[i] == '-')) {
            if (str[i] == '-')
                sign = false;
            i++;
        }
        while (i < str.size() && isdigit(str[i])) {
            if (sign && ((res > INT_MAX/10) || (res == INT_MAX/10 && str[i]-'0' >= INT_MAX%10)))
                return INT_MAX;
            if (!sign && ((res > -(INT_MIN/10)) || (res == -(INT_MIN/10) && str[i]-'0' >= -(INT_MIN%10))))
                return INT_MIN;
            res = 10*res + (str[i++]-'0');
        }
        if (!sign)
            res *= -1;
        return res;
    }

Log in to reply
 

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