My c++ solution


  • 2
    I
    int myAtoi(string str) {
           if (str.empty()) return 0;
            int ans = 0;
            int sign = 1;
            queue<char> q;
        
            size_t first = str.find_first_not_of(' ');
            size_t last = str.find_last_not_of(' ');
            string trimmed = str.substr(first, (last-first+1));
        
            for(auto &c : trimmed) {
                q.push(c);
            }
        
            char n = q.front();
            if (n == '+' || n == '-') {
                q.pop();
                sign = (n == '+') ? 1 : -1;
            }
        
            while(!q.empty()) {
                char c = q.front();
                q.pop();
                if (c < 48 || c > 57) break;
                int temp = ans * 10 + (c-48);
                if (temp / 10 != ans) {
                    if (sign == -1) return INT_MIN;
                    return INT_MAX;
                }
                ans = temp;
            }
            return sign*ans;
    }

Log in to reply
 

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