Why my code always fails on a boundary case?


  • 0

    Alway failed on "2147483648".
    But when I test it locally, it's fine.

    class Solution {
    public:
    int atoi(const char *str) {
    if (str == NULL || *str == '\0') {
    // return 0 when invalid
    return 0;
    }

        int state = 0;
        int sign = 1;
        long int num = 0;
        while (*str != '\0') {
            switch (state) {
                case 0: // skip spaces
                    if (isspace(*str)) {
                    } else if (isdigit(*str)) {
                        num += *str - '0';
                        state = 1;
                    } else if (*str == '+' || *str == '-') {
                        if (*str == '-')
                            sign = -1;
                        state = 2;
                    } else {
                        return 0;
                    }
                    str++;
                    break;
                case 1: // digit found
                    if (isdigit(*str)) {
                        num = num*10 + *str - '0';
                        if (num*sign < INT_MIN) {
                            return INT_MIN;
                        } else if (num*sign > INT_MAX) {
                            return INT_MAX;
                        }
                    } else {
                        return sign*num;
                    }
                    str++;
                    break;
                case 2: // sign found
                    if (isdigit(*str)) {
                        num += *str - '0';
                        state = 1;
                    } else {
                        return 0;
                    }
                    str++;
                    break;
            }
        }
        if(state == 1) {
            return sign*num;
        } else {
            return 0;
        }
    }
    

    };


  • 0
    S

    Could you please format your code correctly? Also remove some cout in your code to make it clear for reading.


  • 0

    no one wants to help?


  • 1
    G

    Depends on your compiler platform, the data type "long int" will be different length. In my environment, it is 4 byte same as int. so you cannot handle overflow.
    change the 3rd line to: long long num = 0, I think it will work.


Log in to reply
 

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