My C++ solution using long


  • 0

    class Solution {
    public:
    int myAtoi(string str) {
    int i = 0;
    while(i < str.size() && str[i] == ' ')
    i++;
    int flag = 1;
    if(str[i] == '-' || str[i] == '+'){
    if(str[i] == '-')
    flag = - 1;
    i++;
    }

        long sum = 0;
        while(i < str.size() && str[i]<= '9' && str[i] >= '0'){
            sum = sum * 10 + str[i] - '0';
            if(flag == 1 && sum > INT_MAX)
                return INT_MAX;
            if(sum * (- 1) < INT_MIN)
                return INT_MIN;
            i++;
        }
        return flag * sum;
    }
    

    };


Log in to reply
 

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