LeetCode – 7. Reverse Integer (Medium)

題目連結 : Reverse Integer – LeetCode

Python
#7. Reverse Integer 字串反轉
class Solution:
    def reverse(self, x: int) -> int:
        if x < 0:
            a = str(x)[:0:-1]
            b = int(a)
            b = b * (-1)
        else:
            a = str(x)[::-1]
            b = int(a)
        
        if b > (2**31-1) or b < (-2**31 - 1):
            return 0
        else: 
            return b 
Python
#7. Reverse Integer 純數字運算

class Solution:
    def reverse(self, x: int) -> int:
        INT_MAX = 2**31 - 1
        INT_MIN = -2**31      
        reversed_number = 0
        sign = 1 if x > 0 else -1
        x = abs(x)

        while x != 0:
            digit = x % 10
            if reversed_number * 10 + digit > INT_MAX:
                return 0  # 檢查是否溢位
            reversed_number = reversed_number * 10 + digit
            x = x // 10

        return reversed_number*sign