C++ 10 lines solution, easy understanding, clean code


  • 11
    L
      int myAtoi(string str) {
        if (str.empty()) return 0;
        int i = 0, sign = 1;
        while (i + 1 < str.size() && isspace(str[i])) ++i;
        long res = 0;
        if (str[i] == '-' || str[i] == '+') sign = 44 - str[i++];
        while (i < str.size()) {
            if (isdigit(str[i])) res = 10 * res + str[i++] - '0';
            else return res * sign;
            if (res > INT_MAX) return sign == -1 ? INT_MIN : INT_MAX;
        }
        return res * sign;
    }

  • 0
    V
    int myAtoi(string str) {
        int i = str.find_first_not_of(' '), s = 1;
        long res = 0;
        if(str[i]=='+'||str[i]=='-') 
            s = (str[i++]=='+')?1:-1;
        while(isdigit(str[i])) {
            res = res*10 + (str[i++]-'0');
            if(res>INT_MAX) return s>0?INT_MAX:INT_MIN;
        }
        return s*res;
    }

  • 1
    S

    your code, input +-2 output -2, but the expected answer is 0, did you pass all test cases?


Log in to reply
 

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