long转int截断问题,截断异常或处理错误

Long to int truncation problem, truncating exceptions or handling error

Leetcode要求将-91283472332的输出转为int,输出结果为-2147483648。我用long来存储结果,然后用return int。为什么结果 returned -1089159116

这是我的代码

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;

}

这是描述

解析后的整数为-91283472332。 由于 -91283472332 小于范围 [-231, 231 - 1] 的下限,最终结果被限制为 - 231 = -2147483648.

-912834723320xFFFFFFEABF14C034 的十六进制,补码。

当截断为32位长时,值为0xBF14C034,解释为补码时表示-1089159116

当值超过限制时,您应该向 return -2147483648 添加一些条件分支。

我猜你在做 this problem. Since it requires values outside the range to be clamped to the maximum values, A.K.A saturated math,你需要像这样检查值的范围

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

类似于C++中的std::clamp(n, INT_MIN, INT_MAX)

你可以在要求中清楚地看到这一点(强调我的):

  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.

现在将其与上面的 if 块进行比较

如果您将值从 64 位转换为 32 位,那么它将以 2n:

为模减少该值
  • -91283472332 % 2147483648 = -1089159116,
  • 或十六进制:0xFFFFFFEA<strong>BF14C034</strong> & 0xFFFFFFFF = 0x<strong>BF14C034</strong>

饱和度数学在数字信号处理或计算机图形学等许多领域都很常见

  • is there a function in C or C++ to do "saturation" on an integer
  • How to do unsigned saturating addition in C?