I found a bug in my code but it was accepted by the judge.


  • 0
    H

    test case : "0 1"

    code :

    int myAtoi(char* str) {
            int ret=0, signs=0, pos=1;
            for (int i=0; str[i]; i++){
                int n = str[i] - '0';
                switch (str[i]){
                    case ' ': if ( signs  > 0 || ret > 0 ) return pos==0?-ret:ret; else break;
                    case '-': if (signs++ > 0) return 0; else { pos=0; break; }
                    case '+': if (signs++ > 0) return 0; else break;
                    default :
                        if ( n < 0  || n > 9 ) return pos==0?-ret:ret; 
                        if ( pos==0 ){
                            /* INT_MIN = - ( INT_MAX + 1 )*/
                            if ( ret == ( INT_MAX - n ) / 10 ) return INT_MIN + 1;
                            if ( ret >  ( INT_MAX - n ) / 10 ) return INT_MIN;
                        }else
                            if ( ret >= ( INT_MAX - n ) / 10 ) return INT_MAX;
                        ret = ret * 10 + n;
                }
            }
            return pos==0?-ret:ret;
    }
    

    Your answer : 1

    Expected answer : 0


Log in to reply
 

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