본문 바로가기

hacking or software engineering skills/leetcode

7. Reverse Integer

728x90

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321

Example 2:

Input: -123 Output: -321

Example 3:

Input: 120 Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

class Solution:
    def reverse(self, x: int) -> int:
        if x == 0:
            return 0
        
        rev_x = str(x)[::-1]


        zero_cnt = 0
        for rx in rev_x:
            if not rx is '0':
                break
            else:
                zero_cnt += 1

        rev_x = rev_x[zero_cnt:]

        if rev_x[-1] == '-':
            rev_x= '-' + rev_x[:-1]

        rev_x = int(rev_x)

        if (rev_x < -pow(2,31)) or (rev_x >= pow(2,31)):
            return 0

        else:
            return rev_x
        

 

더 간단한 3줄 코드

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        sign = [1,-1][x < 0]
        rst = sign * int(str(abs(x))[::-1])
        return rst if -(2**31)-1 < rst < 2**31 else 0