17 ms c++ solution with comments


  • 3
    P
    class Solution {
    public:
        int atoi(string str) {
            int  i = 0;
            int n = str.size();
            //skip white spaces
            while(i < n && str[i] == ' ') {
                i++;
            }
            
            if (i == n) return 0;
            int sign = 1;
            // sign handling
            if (str[i] == '-') {
                sign = -1;
                i++;
            } else if (str[i] == '+') {
                i++;
            }
            
            
            long num = 0;
            // if its too large a number, then stop once it reaches INT_MAX
            while(i < n && num < INT_MAX && isdigit(str[i])) {
                // while its a digit, skip rest
                int d = str[i]-'0';
                num =num*10+d;
                i++;
            }
            
            // out of range handling
            if (num > INT_MAX) {
                return sign == 1 ? INT_MAX : INT_MIN;
            }
            return sign*num;
        }
    };

  • 2
    W

    Hi, I think there exists a bug in your code although you have passed the OJ.

    Noticing that when the string contains only spaces, here you didn't exam the index :

    while(str[i] == ' ') {
        i++;
    }
    

    It will reach the end of the string.

    Also, there still exists problem :

    if (str[i] == '-') {
        sign = -1;
        i++;
    } else if (str[i] == '+') {
    // handle + explicitely
        i++;
    }
    

    It's unsafe to visit the index which has reached the end of the string.

    May be it passed OJ, but I don't think its a strong aoti implement.


  • 0
    P

    Corrected it. Thanks for catching it!


  • 0
    W

    Glad to help you:)


Log in to reply
 

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