Using Long to check INT Range


  • 0
    U
    class Solution {
    public:
        int myAtoi(string str) {
    
            long int result = 0, index = 0, flag = 1;
            int strLen = str.length();
    
            if (strLen == 0) return 0;
    
            while (str[index] == ' ') index++;
            if (str[index] == '-') {
                index++;
                flag = -1;
            }
            else if (str[index] == '+')
                index++;
    
            for (;index < strLen; index++) {
                if (str[index] < '0' || str[index] > '9') break;
    
                result = result * 10 + (str[index] - '0');
                
                if (flag == 1 && result >= INT_MAX) return INT_MAX;
                else if (flag == -1 && -1 * result <= INT_MIN) return INT_MIN;           
            }
            return result * flag;
        }
    };
    

Log in to reply
 

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