Solution for String to Integer (atoi)


  • 0
    V
    class Solution {
    public:
        int myAtoi(string str) {
            bool minus = false;
            int l = 0;
            int n = 0; 
            while(str[l] == ' ') {
                ++l;
            }
            
            if(str[l] == '-')
            {
                minus = true;
                ++l;
            } else if(str[l] == '+') {
                ++l;
            } 
            
            if(str[l] > '9' || str[l] < '0') {
                return 0;
            }
            
            while (str[l] <= '9' && str[l] >= '0') {
                int k = str[l] - '0';
                if(INT_MAX - n < k && minus == false) {
                    return INT_MAX;
                }
                if(INT_MAX - n  < k - 1 && minus) {
                   return INT_MIN;
                }
                n += k;
                if(!(l + 1 == str.size() || str[l + 1] > '9' || str[l + 1] < '0'))
                {
                    if(INT_MAX / 10 < n && minus == false) {
                        return INT_MAX;
                    } 
                    if(INT_MAX / 10 < n && minus) {
                        return INT_MIN;
                    }
                    n *= 10; 
                }        
                ++l;
            }
            
            return minus ? -n : n;
        }
    };
    

Log in to reply
 

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