[LeetCode] Reverse Integer

黃馨平
Jackycsie
Published in
1 min readSep 8, 2020

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解題

這題其實蠻愜意的,需要在乎的是最後的尾數 0 與正負數就可以解決此問題,另外要注意的是 32-bit 的小陷阱,如果超過正負 2147483648,就會傳 0 這點需要注意。

那本題的思維是 check 正負,轉 string ,從最後面讀回來,用 string 的方法相加,就可以囉。

  • Runtime: 28 ms, faster than 37.79%
  • Memory Usage: 12.7 MB, less than 49.07%

另外如果比較 high-level 的 programer 其實可以使用下面方法,蠻不錯的,我個人也比較 prefer 這種寫法,不管是 code review 或者 memory 上都可以節省多一點的資源跟時間,而且又清晰易懂。

  • Runtime: 24 ms, faster than 60.45%
  • Memory Usage: 12.6 MB, less than 90.82%

好文推推:

--

--

黃馨平
Jackycsie

閱讀本是尋常事,繁華靜處遇知音