SW 정글/알고리즘

[math] 7. Reverse Integer

삼월은마치 2024. 10. 23. 13:53

https://leetcode.com/problems/reverse-integer/description/

 

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

 

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

 

Constraints:

  • -231 <= x <= 231 - 1

풀이

class Solution:
    def reverse(self, x: int) -> int:
        
        sign = -1 if x < 0 else 1
        
        reverse_num = str(abs(x))[::-1]
        
        result = sign * int(reverse_num)

        if result < -2**31 or 2**31 < result:
            return 0

        return result

 

 

https://marchislike.tistory.com/248

⬆️앞서 적용했던 슬라이싱 방법을 사용하면 간단할 것 같은데,

문제는 example3을 보았을 때, 변환한 뒤 앞자리에 0이 존재한다면 0을 제거해야 하는 점이다.

그런데 찾아보니 파이썬에서 문자열을 int형으로 변환하면 자동으로 0이 제거된다고 한다..!

 

그래서 처음에 무지성으로 이렇게 구현을 해서 돌렸다가..

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

 

오히려 음수일 경우 부호 처리에 대한 부분을 빼먹었다.

-123을 입력하면 321- 가 아니라 -321이 나와야 한다.

 

 

그래서 reverse num을 저장한 후 해당 reverse num에 대해 다시 부호를 처리해 줘야 한다.

sign = -1 if x < 0 else 1

x가 음수라면 sign = -1 을 넣어줘서 나중에 reverse_num에 곱해서 음수로 만들어준다.

값은 절대값으로 받아야겠다.

 

 

int x에 대해 절대값 abs()으로 받은 후 str으로 형변환하여 슬라이싱을 사용할 수 있도록 한다.

reverse_num = str(abs(x))[::-1]

 

 

 

최종 값에 대해 다시 int형으로 변환한다.

result = sign * int(reverse_num)

 

 

마지막으로 정수 범위 지정에 대한 리턴값도 처리해야 한다.

>> If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

 

if result < -2**31 or 2**31 < result:
	return 0