My Nice Java Code 3ms


  • 16
    public class Solution {
    	public int myAtoi(String str) {
    		if (str.isEmpty())
    			return 0;
    		str = str.trim();
    		int i = 0, ans = 0, sign = 1, len = str.length();
    		if (str.charAt(i) == '-' || str.charAt(i) == '+')
    			sign = str.charAt(i++) == '+' ? 1 : -1;
    		for (; i < len; ++i) {
    			int tmp = str.charAt(i) - '0';
    			if (tmp < 0 || tmp > 9)
    				break;
    			if (ans > Integer.MAX_VALUE / 10
    					|| (ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp))
    				return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    			else
    				ans = ans * 10 + tmp;
    		}
    		return sign * ans;
    	}
    }

  • 0
    H

    And this the following script runs 49ms. I don't know why so big difference in performance?

    public int myAtoi(String str) {
            if (str == null || str.isEmpty()) { return 0; }
            str = str.trim(); // discards whitespace
            char[] chars = str.toCharArray();
            int signum = 1, head = 0;
            if (chars[head] == '+' || chars[head] == '-') { // treat sign
                if (chars[head] == '-') { signum = -1; }
                head++;
            }
            // accumulate
            long result = 0l;
            long max = (long)Integer.MAX_VALUE;
            long min = (long)Integer.MIN_VALUE;
            while (head < chars.length && Character.isDigit(chars[head])) {
                result = (result * 10) + (((int)chars[head++]-'0') * signum); // char '0' = int 48, in ascii
                if (result > 0 && result > max) { result = max; break; }
                if (result < 0 && result < min) { result = min; break; }
            }
            return (int)result;
        }
    

Log in to reply
 

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