easy understand with C


  • 0
    T

    use C and pay more attention to the input format and if the number is valid.
    int myAtoi(const char *str) {
    assert(str!=NULL);
    while(isspace(*str)){
    str++;
    }
    int positive=(*str=='-') ? -1 : 1;
    if(*str=='-' || *str=='+') {
    str++;
    }
    int ret=0;
    while(isdigit(str)){
    int digit=str-'0';
    if(INT_MAX/10 >=ret) {
    ret=ret
    10;
    }
    else{
    return ret= (positive == -1) ? INT_MIN : INT_MAX;
    }
    if(INT_MAX- digit>= ret) {
    ret=ret+digit;
    }
    else{
    return ret= (positive == -1) ? INT_MIN : INT_MAX;
    }
    str++;
    }
    return ret
    positive;
    }


Log in to reply
 

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