For the case: atoi("9223372036854775809")


  • 0
    V

    Hi,
    It seems that my code cannot deal with the test case: "9223372036854775809".

    As I walk through the code step by step, I found that when I do
    result = result*10 + str[i] - '0';

    922337203685477580 + '9' - '0' = -9223372036854775807

    For your information: I declare result as long long type. Here is my code:

    int atoi(const char *str) {
    long long result=0;
    int sign=1, i;
    for (i=0; str[i]==' '; ++i);//skip the spaces

    sign = (str[i]=='-')?(-1):1;
    if (str[i] == '+' || str[i] == '-')
    	i++;
    
    for (result = 0; str[i]>='0' && str[i]<='9'; ++i) {//do if str[i] is a digit.
    	result = 10 * result + (str[i]-'0');
    }
    result *= sign;
    if(result > INT_MAX)  return INT_MAX;
    else if(result < INT_MIN)  return INT_MIN;
    else return result;
    

    }

    Thanks!


  • 0
    O

    you can add your {
    if(result > INT_MAX) return INT_MAX;
    else if(result < INT_MIN) return INT_MIN;

    }in to your for statement.

    Actually at first I met the error like your's.


  • 0
    Q

    i meet the same trouble . could you explain why it is wrong ?


  • 0
    O

    Because it is too long in java such as 2147483649, if you do not add the statement, it will return -2147483647.you can monitor the number if it bigger than 2147483647,than return 2147483647.


  • 0
    Q

    but I have store it in long long


  • 0
    W

    The long long uses 64 bits to store the number and its max value is 9223372036854775808, it means that 9223372036854775809 is overflowed.


  • 0
    A

    bolded text63*2+1


Log in to reply
 

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