Could anyone can explain this tricky thing? Probably related to the platform.


  • 0
    F

    C Solution:

    int myAtoi(char* str) {
        for (; *str == ' ';str++);
        int sign = 1;
        if (*str == '-' || *str == '+') {
            sign = *str++ == '-' ? -1 : 1;
        }
        int limit = INT_MAX / 10;
        int tlimit = INT_MAX % 10;
        int res = 0;
        for (; *str >= '0' && *str <= '9'; str++) {
            if (res > limit || res == limit && *str - '0' > tlimit) {
                return sign == 1 ? INT_MAX : INT_MIN;
            }
            res = res * 10 + *str - '0';
        }
        return sign * res;
    }
    

    This solution will encounter Runtime Error.
    But, if I change res = res * 10 + *str - '0'; to res = res * 10 + (*str - '0');, it will be accepted.

    Anyone has any idea?


Log in to reply
 

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