About as strait forward as I could code it, no tricks, no optomizations (C++)


  • 0
    F
    class Solution {
    public:
        int myAtoi(string str) {
            long ans = 0;
            auto it = str.begin();
            while(*it == ' ') ++it;
            bool isNeg = *it == '-';
            if(*it == '+' || *it == '-') ++it;
            while(*it >= '0' && *it <= '9'){
                ans *= 10;
                ans += *it - '0';
                ++it;
                if(isNeg && 0-ans < INT_MIN){
                    return INT_MIN;
                } 
                else if(!isNeg && ans > INT_MAX){
                    return INT_MAX;
                }
            }
            
            return isNeg ? 0-(int)ans : (int)ans;
        }
    };
    

Log in to reply
 

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