今天要來解的題目是 Leetcode-7. Reverse Integer,難度為 Easy,
而我所使用的語言是 python3
(一個 yahoo 工程師表示,他只刷了 50 題 easy 就有工作了,不要小看 easy 題)
壹、理解題目
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-231, 231 - 1]
, then return 0
.
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Example 4:
Input: x = 0 Output: 0
貳、解題
我最先想到的方法如下:
轉成 string 後,確認是負數或正數,(若是負數,就要處理一下)
最後,確認是否在範圍以內 [-231, 231 - 1]
時間複雜度?
可以參考這篇,裡面除了講「倒轉字串」的方法(包含 python 內建),還比較了時間複雜度喔~
slicing - string[::-1] 就是橘色的點點,在字串長度 < 10000 之前,是最快速的!
這篇也不錯~
參、BONUS
在討論區,看到了一個更加簡潔的方法,只有三行 XDD
以下是我加了註解後的 code,
其中,第一行的 x>0 會是 boolean 值喔(True=1;False=0),
最後一行的 reverse<2**31 也是 boolean 值,所以當 reverse 超過範圍時,就會直接回傳 0
最後是傳統方法