프로젝트들/코딩 테스트
[코딩 테스트] 리트코드 7 - Reverse Integer (Easy) in Python
코곰
2021. 4. 30. 15:56
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
풀이
- 숫자를 문자로 변환해
- 거꾸로 만들되
- 음수라면 앞에 -를 넣어주고
- 다시 숫자로 변환해 반환!
파이썬 코드
class Solution:
def reverse(self, x: int) -> int:
tmp = str(x)
if tmp[0] == '-':
tmp ='-' + tmp[1:][::-1]
else:
tmp = tmp[::-1]
if int(tmp) <-2**31 or int(tmp) > 2**31 - 1:
return 0
return int(tmp)