My Java Solution


  • 0
    F
    public int myAtoi(String str) {
    	if (str == null || str.length() == 0)
    		return 0;
    
    	long res = 0;
    	str = str.trim();
    
    	int index = 0;
    	boolean negative = false;
    	if (str.charAt(0) == '-' || str.charAt(0) == '+') {
    		index++;
    		negative = str.charAt(0) == '-' ? true : false;
    	}
    
    	while (index < str.length() && Character.isDigit(str.charAt(index))) {
    		res = res * 10 + (str.charAt(index) - '0');
    		index++;
    
    		if (res > Integer.MAX_VALUE) {
    			return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
    		}
    	}
    	return negative ? 0 - (int) res : (int) res;
    }

Log in to reply
 

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