My C++ code, with comment. 8ms


  • 7
    W
    class Solution {
    public:
    int myAtoi(string str) {
    
        int ret = 0, tmp;
        int i = 0, flag = 1;
        int len = str.length();
        
        // special case : ""
        if (len == 0) return 0;
        
        // special case : "   (+/-)123"
        while (str[i] == ' ') i++;
        if (str[i] == '-') {
            i++;
            flag = -1;
        }
        else if (str[i] == '+')
            i++;
            
        for (;i < len; i++) {
            if (str[i] < '0' || str[i] > '9') break;
            
            tmp = ret * 10 + str[i] - '0';
            if (tmp / 10 != ret) 
                if (flag == 1) return INT_MAX;
                else return INT_MIN;
    
            ret = tmp;
        }
        
        return ret * flag;
    }
    };

Log in to reply
 

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