Easy-07:整數反轉

整數反轉

  • 解法一:(非數學方法)轉成字符串,反轉,計算結果。通過字符串能夠十分快捷地得到反轉後的數字,而剩下要做的就是將字符串再轉成數字。這種方法是從字符串處理的角度出發的,另外還可以從數學角度出發。
  • 執行用時百分比:48.78%
  • 內存消耗百分比:5.21%
class Solution:
    def reverse(self, x: int) -> int:
        if x == 0:
            return 0
        is_negative = False if x > 0 else True
        x = -x if is_negative else x 
        result = int(str(x).rstrip('0')[::-1])
        result = -result if is_negative else result
        result = result if -(2 ** 31) <= result <= 2 ** 31 else 0
        return result
  • 解法二:(數學方法)彈出和推入數字 & 溢出前檢查。借鑑了官方解法:彈出和推入數字的思路是不需要預先知道給出的整數值有幾位,直接用數學方式即可計算出結果。檢查每一次計算的結果是否溢出,如果溢出則直接返回 0 即可。
  • 執行用時百分比(max):99.65%
  • 內存消耗百分比(max):5.21%
class Solution:
    def reverse(self, x: int) -> int:
        target = -x if x < 0 else x
        result = 0
        limit = 2 ** 31 if x < 0 else 2 ** 31 - 1
        while target > 0:
            result = result * 10 + target % 10
            target //= 10
            if result > limit:
                return 0
        return -result if x < 0 else result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章