Describtion
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).
My Solution
class Solution:
def reverse(self, x: int) -> int:
answer = int(str(x)[::-1]) if x >= 0 else -1 * int(str(-1 * x)[::-1])
if answer <= (2**31 - 1) and answer >= -2**31:
return answer
else:
return 0
숫자를 string으로 바꿔줘 reverse를 해주었다. 이 문제의 포인트는 reversed integer가 int32 범위내에 있어야 한다는 조건을 만족시키는 것이다. 따라서 값을 구한 뒤 range check를 해주었다.
문제 출처 : https://leetcode.com/problems/reverse-integer/
Reverse Integer - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
'Algorithm > Daily Coding Tests Challenge' 카테고리의 다른 글
[Leetcode] Easy : Roman to Integer (0) | 2021.08.30 |
---|---|
[Leetcode] Easy : Palindrome Number (0) | 2021.08.22 |
[프로그래머스 코딩테스트] lv1. 2주차 : 상호 평가 (0) | 2021.08.18 |
[프로그래머스 코딩테스트] lv1. 행렬의 덧셈 (0) | 2021.08.18 |
[프로그래머스 코딩테스트] lv1. 최대공약수와 최소공배수 (0) | 2021.08.18 |