My simple code,is there any improvement?


  • 0
    T

    I code this ,please let me know if there is any improment.

    Runtime: 588 ms

    public int atoi(String str) {
    		String reg = "^\\s*[-+]?[0-9]+.*";
    		if (!str.matches(reg)) {
    			return 0;
    		}
    		str = str.trim();
    		char[] c = str.toCharArray();
    		int i = 0;
    		if (c[0] == '-' || c[0] == '+')
    			i = 1;
    		for (; i < c.length; i++) {
    			if (!(c[i] >= '0' && c[i] <= '9'))
    				break;
    		}
    		char[] cNext = new char[i];
    		for (int j = 0; j < cNext.length; j++) {
    			cNext[j] = c[j];
    		}
    		str = String.valueOf(cNext);
    		try {
    			return Integer.valueOf(str);
    		} catch (NumberFormatException e) {
    			if (c[0] == '-')
    				return Integer.MIN_VALUE;
    			else
    				return Integer.MAX_VALUE;
    		}
    	}

Log in to reply
 

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