leetcode 问题( https://leetcode.com/problems/reverse-integer/description/ )要求反转一个整数,这很简单,但希望用户在出现溢出时返回 0。使用 long 执行此操作也很简单,因为您可以检查它是否大于 java 中的 INTEGER.MAX_INT 或 MIN_INT。但如果只允许 32 位整数,这该如何实现呢?
显示以下解决方案:
public int reverse(int x)
{
int result = 0;
while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}
我很困惑为什么会这样。为什么“反转”操作并将其与之前的结果进行比较可以成功检查溢出?
如果您以 x 开头,则表示: x2 = (x*10) + b,(x2-b)/10 不总是等于 x 吗?由于正溢出总是循环到最小值,而负溢出总是循环到最大值。如何检查溢出?我希望对此有任何澄清。
最佳答案
If you started with x, then said: x2 = (x*10) + b, wouldn't (x2-b)/10 always equal x?
没有。对于加法和减法,您对“循环”的直觉是正确的 - 就像在 12 点左右在钟面上来回移动一样。
但是,这不适用于乘法,如本示例所示:
int x = 2_000_000_000;
int y = x * 10;
int z = y / 10;
System.out.println(x); // 2000000000
System.out.println(z); // -147483648
所以回答最重要的问题:
Why does "reversing" the operation, and comparing it to the previous result successfully check for overflow?
因为当发生溢出时,“反转”这个操作序列不会让你回到输入值。
关于java - 为什么反转操作允许溢出处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849830/