Java - Simple, clean and fast!


  • 5
    J
    public int myAtoi(String str) {
        str = str.trim();
        if (str.isEmpty()) 
        	return 0;
        int sign = 1; int i = 0;
        if (str.charAt(0) == '-' || str.charAt(0) == '+'){
        	sign = (str.charAt(0) == '-')? -1 : 1;
        	if (str.length() < 2 || !Character.isDigit(str.charAt(1))) {
        		return 0;
        	}
        	i++;
         }
        int n = 0;
        while (i < str.length()) {
        	if (Character.isDigit(str.charAt(i))) {
        		int d = str.charAt(i) - '0';
        		if (n > (Integer.MAX_VALUE - d) / 10) { //Detect the integer overflow.
        			n = (sign == -1)? Integer.MIN_VALUE : Integer.MAX_VALUE;
        			return n;
        		}
        		n = n*10 + d;
        	} else {
        		break;
        	}
        	i++;
        }
        return sign * n;
    }

  • 0
    W

    there is a bug when input is -2147483648 (Integer.MIN_VALUE)
    the way you detect the Integer overflow, namely if n > (Integer.MAX_VALUE - d) / 10, now right hand side = 214748363 left hand is 214748364, according to your condition, it should fail, however, in reality, it is still a valid int.


  • 0
    Y

    hi @jinwu, there is an input: "+-2", how do you interpret this? in what case would you see an input like this?


Log in to reply
 

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