My C code using automaton, 4ms


  • 0
    W

    Although this question is quite simple that we can solve it directly. I still recommend using automaton, it is logically clear and is easy to be expanded to recognize like HEX, OCT, BIN numbers and so on.

    0-> waiting for +,-,1-9, to state 1

    1-> calculate value val = val*10 + digit ( except +,- )

    2-> end and return

    int myAtoi(char* str) {
    	
    	const int SPACE = 0;
    	const int ZERO = 1;
    	const int DIGIT = 2;
    	const int OTHERS = 3;
    	const int SIGN = 4;
    	const int delta[2][5] ={
    		{ 0,0,1,2,1 },
    		{ 2,1,1,2,2 }
    	};
    	int len = strlen(str);
    	int input;
    	int state = 0;
    	int val = 0;
    	double vald = 0;
    	int sign = 1;
    	for (int i=0; i < len; i++) {
    		if (str[i] == ' ') input = SPACE;
    		else if (str[i] == '0') input = ZERO;
    		else if (str[i] >= '1' && str[i] <= '9') input = DIGIT;
    		else if (str[i] == '-' || str[i] == '+') {
    			if (str[i] == '-') sign = -1;
    			input = SIGN;
    		}
    		else input = OTHERS;
    		state = delta[state][input];
    		if (state == 1 && input != SIGN) {
    			vald = vald * 10 + str[i] - '0';
    			if (vald >= pow(2, 31)) return sign == 1 ? INT_MAX : INT_MIN;
    		} else if (state == 2) break;
    	}
    	return vald * sign;
    }

Log in to reply
 

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