String to Int, why I cannot use long to store result?


  • 0
    A

    Here in my solution,
    if I change the result to be long type, I will fail
    on this test case

    Input:
    "9223372036854775809"
    Output:
    -2147483648
    Expected:
    2147483647

    but Double type works fine?
    Can anyone explain the message behind this? thanks

     public class Solution {
            public int myAtoi(String str) {
                if (str == null || str.length() < 1)
        		return 0;
         
            	// trim white spaces
            	str = str.trim();
             
            	int sign = 1;
             
            	// check negative or positive
            	int i = 0;
            	if (str.charAt(0) == '-') {
            		sign = -1;
            		i++;
            	} else if (str.charAt(0) == '+') {
            		i++;
            	}
            	// use double to store result
            	double result = 0;
             
            	// calculate value
            	while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            		result = result * 10 + (str.charAt(i) - '0');
            		i++;
            	}
             
            	result *= sign;
             
            	// handle max and min
            	if (result > Integer.MAX_VALUE)
            		return Integer.MAX_VALUE;
             
            	if (result < Integer.MIN_VALUE)
            		return Integer.MIN_VALUE;
             
            	return (int) result;
            }
        }

  • 0
    R

    Int is 32 bit, so any value above 2147483647 is overflow and the output should be the max_int value which is 2147483647. Similarly its -2147483648 for -ve.


Log in to reply
 

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