본문 바로가기

자료구조&알고리즘/알고리즘-문제풀이

Leetcode-easy-7. Reverse Integer

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

        intToString = str(x)

        # zero check
        if len(intToString) == 1:
            return x
        elif intToString[-1] == '0':
            intToString = intToString[:-1]

        # sign check
        flag = False
        if intToString[0] == '-':
            flag = True
            intToString = intToString[1:]

        reverseList = reversed([intToString[idx] for idx in range(0, len(intToString))])
        reverse = int(''.join(reverseList))

        if reverse.bit_length() < 32:
            if flag:
                return reverse * -1
            else:
                return reverse
        else:
            return 0
반응형