C++ 5 lines O(n) clean solution with comments


  • 0
    int myAtoi(string str) {
            // sign is to record +/- if any in str; num is the number value; pos is the progress position in str
            long sign = 1, num = 0, pos = 0;
            
            // skip initial space
            while (pos < str.length() && str[pos] == ' ') { pos++; }                        
            
            // extract sign if any
            if (pos < str.length() && (str[pos] == '+' || str[pos] == '-')) { sign = str[pos++] == '-' ? -1 : 1; }    
            
            // extract number if any, stop if num exceeds INT_MAX boundary
            while (pos < str.length() && isdigit(str[pos]) && num <= INT_MAX) {  num = num * 10 + (str[pos++] - '0'); }
            
            // make sure answer does not exceed int boundary
            return sign == 1 ? min(num, (long)INT_MAX) : max(-num, (long)INT_MIN);
    }
    

Log in to reply
 

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