![](/img/trans.png)
[英]LeetCode 7: Reverse Integer | why does it work with a long but not with an int?
[英]Reverse Integer leetcode: Why does overflow occur only if 7 or greater is added to INT_MAX?
我有Leetcode提供的解決方案,而令我感到困惑的部分是,在Integer.MAX_VALUE中添加7(或更低的值)或在Integer.MIN_VALUE中添加-8(或更低的值)不會導致上溢或下溢分別。
我的邏輯是,如果您具有Integer.MAX_VALUE,則加1將導致溢出。 並且如果您有Integer.MIN_VALUE,則減1將導致下溢。 我對上溢和下溢的理解錯在哪里?
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
是的,通常向Integer.MAX_VALUE
加1會導致溢出,也會從Integer.MIN_VALUE
減去1。 但這不是這里發生的事情。
此代碼執行的整數除以10
,這會將任何小數部分都截斷。 將Integer.MAX_VALUE
( 2147483647
)除以10時,該代碼預期將乘以10並加下一位。 該商為214748364
,乘以10
為2147483640
,並且可以加上另外的7而不會溢出。 類似地,在負方面,將Integer.MAX_VALUE
( -2147483648
)除以10將產生-214748364
,再乘以10將產生-2147483640
,並且可以加上另一個-8
而不會溢出。
該代碼考慮了Integer
值范圍的極值的最后一位,並小心地避免了溢出。
Integer.MAX_VALUE
是2147483647
這意味着: Integer.MAX_VALUE/10
為214748364
您將要做: rev = rev * 10 + pop
因此,如果rev > 214748364
,則rev * 10
將導致溢出。
或者,如果rev == 214748364
,則rev * 10
為2147483640
,如果pop > 7
,則rev * 10
rev * 10 + pop
將導致溢出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.