Str To Integer


  • 0
    D
    class Solution {
        public int myAtoi(String str) {
    		if (str == null || "".equals(str)) return 0;
    		str = str.trim();
    		int sign = 1;
    		if (str.startsWith("-")) {
    			str = str.substring(1);
    			sign = -1;
    		} else if (str.startsWith("+")) {
    			str = str.substring(1);
    			sign = 1;
    		}
    		int base = 0;
    		int i = 0;
    		while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
    			if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && (str.charAt(i) - '0') > 7)) {
    				if (sign == 1) {
    					return Integer.MAX_VALUE;
    				} else {
    					return Integer.MIN_VALUE;
    				}
    			}
    			base = base * 10 + (str.charAt(i++) - '0');
    		}
    		return sign * base;
    	}
    }
    

Log in to reply
 

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