얼렁뚱땅 스며드는 Data Science

Algorithm/Daily Coding Tests Challenge

[Leetcode] Easy : Reverse integer

Jesip14 2021. 8. 20. 16:54

Describtion

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).

 

My Solution

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

숫자를 string으로 바꿔줘 reverse를 해주었다. 이 문제의 포인트는 reversed integer가 int32 범위내에 있어야 한다는 조건을 만족시키는 것이다. 따라서 값을 구한 뒤 range check를 해주었다. 

 

문제 출처 : https://leetcode.com/problems/reverse-integer/

 

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