My accepted Java code, looked redundant but considered all cases


  • 4
    S
    public class Solution {
    public int atoi(String str) {
        boolean neg = false; // flag to mark if the converted integer positive or negative. 
        StringBuilder buf = new StringBuilder(); // temp buffer to store the converted string
        
        // check if the string is null or empty
        if (str == null || str.isEmpty()) return 0;
        
        // trim the leading whitespaces
        str = str.trim();
        
        // if string contains only whitespace characters
        if (str.isEmpty()) return 0;
        
        // get length of the trimed string
        int length = str.length();
        
        // Check if the first character of the string
        if (isNeg(str.charAt(0))) neg = true;
        else if (isPos(str.charAt(0))) neg = false;
        else if (Character.isDigit(str.charAt(0))) buf.append(str.charAt(0));
        else return 0;
        
        // check the first sequence of digit characters in the string
        int start = 1;
        while (start < length && Character.isDigit(str.charAt(start))) {
            buf.append(str.charAt(start));
            start++;
        }
        
        // check if the buf is empty
        if (buf.length() == 0) return 0;
        
        // check if the converted integer is overflowed
        long result;
        if (buf.length() <= 10) {
            result = toInteger(buf, neg);
        } else if (neg) {
            return Integer.MIN_VALUE;
        } else
            return Integer.MAX_VALUE;
            
        // Post-processing the convert long to int
        if (neg && result <= Integer.MAX_VALUE) {
            return 0 - (int) result;
        } else if (!neg && result <= Integer.MAX_VALUE) {
            return (int) result;
        } else if (neg && result > Integer.MAX_VALUE) {
            return Integer.MIN_VALUE;
        } else return Integer.MAX_VALUE;
    }
    
    private boolean isPos(char ch) {
        return ch == '+';
    }
    
    private boolean isNeg(char ch) {
        return ch == '-';
    }
    
    private long toInteger(StringBuilder buf, boolean neg) {
        int len = buf.length();
        long result = 0;
        for (int i = 0; i < len; i++) {
            result += Character.getNumericValue(buf.charAt(i)) * Math.pow(10, len - i - 1);
        }
        
        return result;
    }
    

    }


  • 8
    Z

    my solution with the comments.

    public class Solution {
        public int atoi(String str) {
            if (str == null || str.length() == 0)
        		return 0;
        	// trim white-spaces
        	str = str.trim();
        	// determine positive/negative, value is +/- 1
        	int flag = 1;
        	int i = 0;
        	if (str.charAt(0) == '+') {
        		flag = 1;
        		i++;
        	} else if (str.charAt(0) == '-'){
        		flag = -1;
        		i++;
        	}
        	// calculate the value
            // to avoid overflow of integer, use double and then determine 
            // whether the value is over Integer.MAX_VALUE
        	double res = 0;
        	while (i < str.length() && str.charAt(i) - '0' <= 9 && str.charAt(i) - '0' >= 0) {
    			res = res * 10 + (str.charAt(i) - '0');
    			i++;
    		}
    	
    		res *= flag;
    		if (res > Integer.MAX_VALUE) {
    			res = Integer.MAX_VALUE;
    		} else if (res < Integer.MIN_VALUE) {
    			res = Integer.MIN_VALUE;
    		}
    		return (int) res;
        }
    }

  • 0
    S

    Nice solution!

    But one thing I think you need to handle is in the while loop, What if the too-long string even overflowed the double type? So I think it needs to change the while loop as
    while (i < str.length() && i <= 11&& Character.isDigit(str.charAt(i))). Since the MAX_VLAUE and MIN_VALUE has 10 digits, it is safe to just check the first 11 characters in the string.


  • 1
    Y

    I think we only need to handle fourcases:

    1. discards all leading whitespaces
    2. sign of the number
    3. overflow
    4. invalid ipnut
    int atoi(const char *str) {
        int sign = 1, base = 0, i = 0;
        while (str[i] == ' ') { i++; }
        if (str[i] == '-' || str[i] == '+') {
            sign = 1 - 2 * (str[i++] == '-'); 
        }
        while (str[i] >= '0' && str[i] <= '9') {
            if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
                if (sign == 1) return INT_MAX;
                else return INT_MIN;
            }
            base  = 10 * base + (str[i++] - '0');
        }
        return base * sign;
    }

  • 0
    A

    did you handle pointer go beyond string length? it seems that you assumed anything beyond str array boundary would be non digital?


  • 0
    Y

    We should ignore all chars that do not contribute a valid number(including '\0'), just like atoi function. :P


  • 0
    A

    you are correct, i forgot the input string will be properly terminated by '\0'. using the same concept, i actually came up with a quite neat java version solution. note, java string doesn't have the '\0' explictly appended, so i appended a special char at the end of the input string in java, and enjoyed the fact that i don't have to check going off boundary all the time.


Log in to reply
 

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