LeetCode - The World's Leading Online Programming Learning Platform
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
1. 문제 파악
Given an integer x, return true if x is a palindrome, and false otherwise.
숫자 x가 주어졌을 시 해당숫자가 palindrome이라면 true 아니라면 false를 반환하시오
* palindrome 이란? -- 회문(回文) 또는 팰린드롬(palindrome)은 거꾸로 읽어도 제대로 읽는 것과 같은 문장이나 낱말, 숫자, 문자열(sequence of characters) 등이다.
2. 예시
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.
3. 풀이 코드
- 해당 문제를 쉽게 풀기 위한 방법은 int를 문자열로 변환 한 뒤에 풀어야 한다.
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 10 and x >= 0:
return True
if x < 0 or x % 10 == 0:
return False
num = str(x)
st = []
ln = len(num) - 1
for i in range((ln + 1)//2):
if num[i] != num[ln-i]:
return False
return True
class Solution:
def isPalindrome(self, x: int) -> bool:
if str(x) == str(x)[::-1]:
return True
return False
Python을 이용한 간결한 코드로는 다음이 있습니다.
문자열 슬라이싱을 이용한 것으로 슬라이싱과 관련된 이론은 다음에 있습니다.
02-2 문자열 자료형
`[동영상 강의]` : [점프 투 파이썬 02-2 문자열](https://www.youtube.com/watch?v=cKjE94_CITc&list;=PLGSQkvB9T6rvnDo…
wikidocs.net
슬라이싱을 이용해 문자열을 뒤집은 다음 둘이 같음 바로 True 아닌 경우 False를 반환하는 코드입니다.
'알고리즘 문제 > 리트코드' 카테고리의 다른 글
LeetCode 1번 문제 : Two Sum python 풀이 (0) | 2024.02.05 |
---|