본문 바로가기
💻 LEETCODE

[LEETCODE] 9. Palindrome Number

by 구라미 2022. 11. 22.

 

 

 

Given an integer x, return true if x is a palindrome, and false otherwise.

 

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?

 

 

내 풀이

class Solution:
    def isPalindrome(self, x: int) -> bool:
        num = str(x)
        mid = ceil(len(num) / 2)
        
        if len(num) == 1:
            return True

        if len(num)%2 == 0:
            if num[:mid] == num[mid:][::-1]:
                return True
            else:
                return False
        else:
            if num[:mid] == num[mid-1:][::-1]:
                return True
            else:
                return False

 

 

 

다른 풀이

원리는 비슷한데 초 심플하다..

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

 

def isPalindrome(self, x: int) -> bool:
	if x<0:
		return False

	inputNum = x
	newNum = 0
	while x>0:
		newNum = newNum * 10 + x%10
		x = x//10
	return newNum == inputNum

 

 

 

댓글