🧠 Reverse Integer

문제

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 [-2 to the 31, 2 to the 31 - 1], then return 0.

  • -2 to the 31 <= x <= 2 to the 31 - 1

λ‚˜μ˜ 풀이

def reverse(self, x: int) -> int:
    result = -int(str(x)[1:][::-1]) if x < 0 else int(str(x)[::-1])
    if -2 ** 31 <= result <= (2 ** 31) - 1:
        return result
    return 0

λ‚˜λŠ” λ¬Έμžμ—΄ μŠ¬λΌμ΄μ‹±μ„ 톡해 ν•΄κ²°ν–ˆλ‹€.

λ‹€λ₯Έ μ‚¬λžŒμ˜ 풀이

def reverse(self, x: int) -> int:
    rev = int(str(abs(x))[::-1])
    return (-rev if x < 0 else rev) if rev.bit_length() < 32 else 0

파이썬의 intμ—λŠ” bit_length()λΌλŠ” λΉ„νŠΈ 길이λ₯Ό λ¦¬ν„΄ν•΄μ£ΌλŠ” ν•¨μˆ˜κ°€ μžˆμ—ˆλ‹€!

References


Written by@ugaemi
Record things I want to remember

🐱 GitHubπŸ“š Reading Space