0

Leetcode requires that the output of -91283472332 be converted to int, and the output result is -2147483648. I use long to store the result, and then return int. Why is the result returned -1089159116

here's my code

int myAtoi(char * s){
    char *str = s;
    long n = 0;
    char *flag ;
    while(*str){
        if( * str =='-' || * str == '+')
        {
            flag = str++;
            continue;
        }
        if(*str<='9' && *str>='0')
        {
            n*=10;
            n+=(*str++)-48;
            continue;
        }
        if(*str>='A'&&*str<='z')
            break;
        
        ++str;

    }
    if(*flag == '-')
    {
        n-=(2*n);
    }
    return n;

}

So here's the description

  • Input: s = "-91283472332"
  • Output: -2147483648
  • Explanation:
    • Step 1:

      "-91283472332" (no characters read because there is no leading whitespace)
       ^
      
    • Step 2:

      "-91283472332" ('-' is read, so the result should be negative)
        ^
      
    • Step 3:

      "-91283472332" ("91283472332" is read in)
                   ^
      

The parsed integer is -91283472332. Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648.

phuclv
  • 37,963
  • 15
  • 156
  • 475
XiaoTian
  • 45
  • 5

2 Answers2

0

The value -91283472332 is 0xFFFFFFEABF14C034 in hexadecimal, two's complement.

When it is trunctated to 32-bit long, the value is 0xBF14C034 and it means -1089159116 when interpreted as two's complement.

You should add some conditional branch to return -2147483648 when the value exceeds the limit.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

I guess you're doing this problem. Since it requires values outside the range to be clamped to the maximum values, A.K.A saturated math, you'll need to check the value's range like this

if (n > INT_MAX)
    return INT_MAX;
else if (n < INT_MIN)
    return INT_MINT;
else
    return n;

It's similar to std::clamp(n, INT_MIN, INT_MAX) in C++

You can see that clearly in the requirements (emphasis mine):

  1. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.

Now compare that with the above if blocks

If you cast the value from 64 to 32-bit then it'll reduce the value modulo 2n:

  • -91283472332 % 2147483648 = -1089159116,
  • or in hex: 0xFFFFFFEABF14C034 & 0xFFFFFFFF = 0xBF14C034

Saturation math is common in many areas like digital signal processing or computer graphics

phuclv
  • 37,963
  • 15
  • 156
  • 475