본문 바로가기
IT/LeetCode

[LeetCode] 9. Palindrome Number

by 강천구 2022. 7. 20.

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

주어진 Integer 숫자 x가 앞뒤로 같은(palindrome) 여부를 확인하는 문제이다.

Example과 같이 음수의 경우 무조건 False일 수 밖에 없다.

양수의 경우 x를 str로 변환 후 [::-1]을 이용하여 뒤집은 후 int()를 통해 정수로 변환한다.

그 후 기존의 x와 뒤집은 수가 같다면 True 다르다면 False를 반환하는 로직이다.

class Solution:
   def isPalindrome(self, x):
       if x < 0:
           return False
       else:
           xtoString = x.__str__()
           revX = xtoString[::-1]
           answer = int(revX)
           if answer == x:
               return True
           else:
               return False

 

 

문제 출처 : https://leetcode.com/problems/palindrome-number/

 

Palindrome Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_9.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 14. Longest Common Prefix  (0) 2022.07.21
[LeetCode] 13. Roman to Integer  (0) 2022.07.21
[LeetCode] 7. Reverse Integer  (0) 2022.07.20
[LeetCode] 5. Longest Palindromic Substring  (0) 2022.07.20
[LeetCode] 1. Two Sum  (0) 2022.07.20

댓글