1. 程式人生 > >【LeetCode】7.Reverse Integer 整數反轉

【LeetCode】7.Reverse Integer 整數反轉

示例1:

Input: 123
Output: 321

注意:

假設我們的環境只能儲存得下 32 位的有符號整數,則其數值範圍為 [−231,  231 − 1]。請根據這個假設,如果反轉後整數溢位那麼就返回 0。

解題思路:

以後過於簡單的題不寫進部落格了。

if x < 0:
    res = - int(str(x)[: 0: -1])
    if res < - 2 ** 31:
        return 0
    return res
else:
    res = int(str(x)[: : -1])
    if res > 2 ** 31 - 1:
        return 0
    return res

72 ms,打敗了44.30%的對手。

解題思路2:

排名靠前的前輩,使用了abs函式取絕對值。