iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

LeetCode 每日一題挑戰系列 第 7

7. Reverse Integer

  • 分享至 

  • xImage
  •  

今天的題目是 Reverse Integer。
題目很直白,就是把一個整數的數字反轉,例如:

123 → 321

-123 → -321

120 → 21

但裡面有一個陷阱:因為數字是 32-bit 整數,反轉後可能會超過範圍,例如 1534236469,反轉之後會爆掉,所以要檢查溢出的情況,超過範圍就要回傳 0。

思路

一開始我腦袋閃過「轉成字串再反轉」的作法,但題目限制環境不能用超過 32-bit 的數字,所以還是得用數學方式處理。

步驟大概是:

用 x % 10 拿到最後一位數字。

用 x / 10 去掉最後一位。

不斷組合新數字 rev = rev * 10 + pop。

每次組合前檢查 rev 有沒有超過 32-bit 整數範圍。

https://ithelp.ithome.com.tw/upload/images/20250920/201695379xlR4qt6Dr.pnghttps://ithelp.ithome.com.tw/upload/images/20250920/20169537bFEZUxUDif.pnghttps://ithelp.ithome.com.tw/upload/images/20250920/20169537KeI19pAWO9.pnghttps://ithelp.ithome.com.tw/upload/images/20250920/201695378SnSBvc4R2.png
程式碼 (Java)
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10; // 取最後一位
x /= 10; // 去掉最後一位

        // 溢出檢查 (32-bit)
        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;
}

}

心得

這題表面上很簡單,實際寫起來要注意的地方還不少:

如果沒有處理 溢出,程式會直接跑錯。

Java 的 int 本身就是 32-bit,所以很適合練習「邊界檢查」。

學到一個小技巧:在組合數字前,先用 Integer.MAX_VALUE / 10 來檢查,不用額外開 long。

雖然題目標示是「Medium」,但我覺得算是送分題,重點在於熟悉數字處理跟防溢出思維。


上一篇
Day 5 - Zigzag Conversion
下一篇
LeetCode 鐵人賽 Day 7 — String to Integer (atoi)
系列文
LeetCode 每日一題挑戰9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言