iT邦幫忙

3

自主學習30日-LeetCode 7.Reverse Integer

  • 分享至 

  • xImage
  •  

7.Reverse Integer

題目描述

給你一個 32 位整數 x,將其數字反轉。

例如:123 → 321,-123 → -321

如果反轉後的數字超過 32 位整數範圍([-2³¹, 2³¹-1]),返回 0。

解題思路

初始化 rev = 0

每次取出 x 的最後一位 pop = x % 10

更新 x = x / 10

將 pop 加到 rev 的末位:rev = rev * 10 + pop

反轉過程中檢查溢出:

如果 rev > Integer.MAX_VALUE/10 或 rev < Integer.MIN_VALUE/10,直接返回 0

https://ithelp.ithome.com.tw/upload/images/20250924/20169298CO76toiTcQ.pnghttps://ithelp.ithome.com.tw/upload/images/20250924/20169298180xXrqDr4.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言