JAVA - Why is this not working?


  • 0
    T

    My code fails the "2147483648" test. It outputs -2147483648 instead of 2147483647.

    '''
    public class Solution {
    public int myAtoi(String str) {

        int result = 0;
        int i = 0;
        boolean negative = false;
        
        str = str.trim();
        
        if(i < str.length() && str.charAt(i) == '-'){
            negative = true;
            i++;
        }
        
        else if(i < str.length() && str.charAt(i) == '+')
            i++;
    
        int newResult;
        while(i < str.length() && (str.charAt(i) >= '0' && str.charAt(i) <= '9')){
            
            if(negative) newResult = result * 10 - (str.charAt(i) - '0');
            else newResult = result * 10 + (str.charAt(i) - '0');
            
            if(negative && newResult < Integer.MIN_VALUE)
            	return Integer.MIN_VALUE;
            else if(!negative && newResult > Integer.MAX_VALUE)    	
            	return Integer.MAX_VALUE;
         
            result = newResult;
            i++;
        }
        
        return result;
    }
    

    }
    '''

    The problem comes from the boolean statement "else if newResult > Integer.MAX_VALUE", java does not find this boolean statement to be true. As a result, the code loops out of the while loop since it reached the last character in the string and prints the current result.
    I find it odd that it doesnt work, considering I saw another working solution:
    '''
    public static int myAtoi(String str) {
    if (str == null || str.length() == 0)
    return 0;//
    str = str.trim();
    char firstChar = str.charAt(0);
    int sign = 1, start = 0, len = str.length();
    long sum = 0;
    if (firstChar == '+') {
    sign = 1;
    start++;
    } else if (firstChar == '-') {
    sign = -1;
    start++;
    }
    for (int i = start; i < len; i++) {
    if (!Character.isDigit(str.charAt(i)))
    return (int) sum * sign;
    sum = sum * 10 + str.charAt(i) - '0';
    if (sign == 1 && sum > Integer.MAX_VALUE)
    return Integer.MAX_VALUE;
    if (sign == -1 && (-1) * sum < Integer.MIN_VALUE)
    return Integer.MIN_VALUE;
    }

    return (int) sum * sign;
    

    }
    '''
    where the person pretty much uses the same check for out of range values...

    Can somewhat tell me what went wrong with my code?

    Thanks


Log in to reply
 

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