LeetCode :Reverse Integer

최대 1 분 소요

문제

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

Example 4:

Input: x = 0
Output: 0

정답 풀이

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

핵심 알고리즘 및 스킬

  • str(x)[::-1]의 의미
  • str(x*-1)[::-1]의 의미

배워야할 점

  • The Slice notation in python has the syntax
  • list[::]

Example

a = ‘1234’
a[::-1]
‘4321

[출처] : https://stackoverflow.com/questions/31633635/what-is-the-meaning-of-inta-1-in-python/31633656

카테고리:

업데이트:

댓글남기기