Wondering what is the fastest solution


  • 0

    here is my code, and I am wondering what is the best solution, any ideas?

    public int myAtoi (String str) {
    	str = str.trim ();
    	if (str.isEmpty ()) {
    		return 0;
    	}
    	boolean minus  = str.charAt (0) == '-';
    	boolean plus   = str.charAt (0) == '+';
    	long    result = 0;
    	for (int ii = (minus || plus) ? 1 : 0; ii < str.length (); ii++) {
    		if (str.charAt (ii) > '9' || str.charAt (ii) < '0') {
    			break;
    		}
    		result *= 10;
    		result += str.charAt (ii) - '0';
    		if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
    			// OVERFLOW! don't need further conversion
    			break;
    		}
    	}
    	result = minus ? -result : result;
    	if (result > Integer.MAX_VALUE) {
    		return Integer.MAX_VALUE;
    	} else if (result < Integer.MIN_VALUE) {
    		return Integer.MIN_VALUE;
    	}
    	return (int)result;
    }

Log in to reply
 

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