본문 바로가기

Algorithm

[LeetCode/Python] Reverse Integer

문제 설명

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.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

 

예시

 

제한

  • -231 <= x <= 231 - 1

 

 

Reverse Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이

class Solution:
    def reverse(self, x: int) -> int:
        answer = 0
        if x < 0:
            answer =  -int(str(x)[1:][::-1])
        else:
            answer = int(str(x)[::-1])
        
        if answer < -2**31 or answer >  2**31 - 1:
            return 0
        return answer