산타는 없다

[리트코드 / LeetCode] 7. Reverse Integer 풀이 - python3 본문

코딩테스트/리트코드

[리트코드 / LeetCode] 7. Reverse Integer 풀이 - python3

LEDPEAR 2021. 1. 1. 18:11
반응형

문제 원문

Given a 32-bit signed integer, reverse digits of an integer.
Note:Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [-2³¹,  2³¹ − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
 
Example 1:
    Input: x = 123 Output: 321
Example 2:
    Input: x = -123 Output: -321
Example 3:
    Input: x = 120 Output: 21
Example 4:
    Input: x = 0 Output: 0
 
Constraints:
    -2³¹ <= x <= 2³¹ - 1

코드 원문

class Solution:
    def reverse(self, x: int) -> int:
        

풀이

입력받은 숫자를 뒤집어서 반환하는 문제입니다. 이번엔 파이썬으로 작성해보았습니다.

맨 앞에 -가 붙었을 때만 -를 빼서 뒤집은 다음 다시 붙여줬습니다.

그리고 결과값이 -2³¹ <= x <= 2³¹ - 1 조건을 벗어날 때 0으로 반환하여 줍니다.

성공 코드

class Solution:
    def reverse(self, x: int) -> int:
        import math
        digit = 0
        Negative = False

        if x < 0:
            x = -x
            Negative = True

        num = str(x)

        if Negative:
            num = num[0:]

        answer = ""
        for i in num:
            answer = i + answer

        if Negative:
            answer = '-' + answer

        answer = int(answer)
        
        if answer >= 2**31-1 or answer <= -2**31 : return 0
        else :  return answer

결과

Runtime: 32 ms, faster than 65.93% of Python3 online submissions for Reverse Integer.

Memory Usage: 14.1 MB, less than 64.13% of Python3 online submissions for Reverse Integer.

반응형
Comments