본문 바로가기
Leetcode

[LeetCode] Palindrom Number 파이썬 (reverse str)

by YGSEO 2021. 3. 25.
728x90
class Solution:
    def isPalindrome(self, x: int) -> bool:
        if str(x) == str(x)[::-1]:
            return True
        else:
            return False

Revese Integer에 있던 str reverse 활용함

 

메모리에서는 50%인데

 

시간 상위 솔루션은

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0:
            print("False")
        else:
            return str(x) == str(x)[::-1]

이런식으로 음수는 다르기 때문에 조건을 줘서 계산을 안하도록.

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        if x == x[::-1]:
            return True
        return False

str전환을 한번만해서 빠르게 계산되도록

 

메모리 측면에서의 상위 솔루션

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        if x < 10:
            return True
        original = x
        reverse = 0
        while x > 0:
            reverse = reverse * 10 + (x % 10) 
            x = x // 10

        return reverse == original

10으로 나눈 나머지를 10으로 계속 곱해주고 다시 나머지를 구하고,

x는 10으로 계속 나눈 몫으로 업데이트해주면서

reversed는 1자리 10자리 100자리 순으로 update되면서 reversed한 결과가 나오게 된다.

728x90

댓글