본문 바로가기
스터디 공간

[Python-Leetcode] 9. Palindrome Number (difficulty : Easy - ☆)

by 재스민맛 2022. 4. 27.
반응형

문제 설명

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

  • For example, 121 is a palindrome while 123 is not.

 

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

 

Constraints:

  • -231 <= x <= 231 - 1

 

Follow up: Could you solve it without converting the integer to a string?

 

문제 풀이

파이썬의 string으로 받아 서  s[::-1]==s를 확인하는 방법의 경우 간단하게 풀수 있으나 그러면 재미가 없으므로 다른 방법으로 해결해보려고 합니다. 재귀함수를 이용해서 풀어보는 방법을 공부해보겠습니다.

1) 방법1

class Solution:
    def isPalindrome(self, x: int) -> bool:
        self.x = str(x)
        return Solution.findpal(self.x)   
        
    @staticmethod
    def findpal(s:str):
        if s[0] != s[-1]:
            return False
        else:
            if s[1:-1] == '':
                return True
            elif len(s[1:-1])==1:
                return True
            return Solution.findpal(s[1:-1])

2) 방법2

class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = str(x)

        for i in range(len(s)):
            if s == '' or len(s)==1:
                return True

            elif s[0]==s[-1]:
                s = s[1:-1]
            
            else:
                return False

 

반응형

댓글