iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0
自我挑戰組

leetcode系列 第 7

leetcode 7. Reverse Integer

  • 分享至 

  • xImage
  •  

題目:
https://ithelp.ithome.com.tw/upload/images/20250921/20169340JXGHTsDd0y.pnghttps://ithelp.ithome.com.tw/upload/images/20250921/20169340NigiDnlY6u.png
https://ithelp.ithome.com.tw/upload/images/20250921/20169340s9A9T3ZGhx.png

解題思路:
取末位數:用 pop = x % 10 取出最後一位。

去掉末位:x = x / 10。

拼接到結果:rev = rev * 10 + pop。

檢查溢位:在更新 rev 前,判斷 rev 是否會超過範圍。

32-bit 最大值:2147483647 (即 Integer.MAX_VALUE)

32-bit 最小值:-2147483648 (即 Integer.MIN_VALUE)

判斷條件:

如果 rev > Integer.MAX_VALUE/10 或者 rev == Integer.MAX_VALUE/10 && pop > 7 → 溢位。

如果 rev < Integer.MIN_VALUE/10 或者 rev == Integer.MIN_VALUE/10 && pop < -8 → 溢位。


上一篇
leetcode 6. Zigzag Conversion
下一篇
leetcode 8. String to Integer (atoi)
系列文
leetcode8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言