Fast C++ code with comments


  • 0
    H
    class Solution {
    public:
        int myAtoi(string str) {
            int len = str.length();
            if (!len) return 0;
            int i = 0;
            while (i < len && str[i] == ' ') i++;
            if (i == len) return 0; // string contains only whitespace
            int pos = 1; // indicates whether it is an positive integer
            if (str[i] == '-') {
                pos = 0; // s[i] is the first non-whitespace character
                i++;
            }
            else if (str[i] == '+') i++;
            int out = 0;
            while (i < len) {
                int temp = (int)(str[i] - '0');
                if (temp < 0 || temp > 9) return (pos ? out : -out);
                else {
                    int temp2 = out * 10 + temp;
                    if (temp2 / 10 != out) return (pos ? INT_MAX : INT_MIN); // avoid overflow
                    else out = temp2;
                }
                i++;
            }
            return (pos ? out : -out);
        }
    };
    

  • 0
    P

    I am not sure why do you have to use int function. Is there someway to get around it?


  • 0
    H

    @pg2286 Yes, you are right. You don't need the int function, the function will do exactly the same thing as "temp" is claimed to be int.


Log in to reply
 

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