8ms C++ solution assume ASCII


  • 2
    Y
    class Solution {
    public:
        int myAtoi(string str) {
            int ret = 0, j = 0;
            bool neg = false;
            while(str[j] == ' ') ++j; // skip whitespace
            if(str[j] == '+' || str[j] == '-') {
                switch (str[j]) {
                    case '-': neg = true;
                }
                j++;
            }
            for(int i = j; i < str.size(); i++) {
                // assume ASCII
                if(str[i] < '0' || str[i] > '9') break;
                int digit = (str[i] - '0');
                if(ret > (INT_MAX-digit)/10) {
                    if(neg) return INT_MIN;
                    return INT_MAX;
                }
                ret = ret * 10 + digit;
            }
            if(neg) return -ret;
            return ret;
        }
    };

  • 1
    D

    Hello,@yutong2, could you please tell me what the usage of ret>INT_MAX/10 and ret*10>INT_MAX-digit ?Didn't they mean the same thing?


  • 0
    Y

    Hello ,I think you are right.
    I tested the code.
    u can just use ret > (INT_MAX-digit)/10


  • 0
    Y

    You're right, ret > (INT_MAX-digit)/10 is sufficient to capture the case. I will update the code accordingly


Log in to reply
 

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