ML , DL (2019)/알고리즘
LeetCode 9. Palindrome Number
초보코더
2023. 8. 17. 14:44
반응형
간단하고 많이쓰이는 회문수 찾기 문제이다.
https://leetcode.com/problems/palindrome-number/description/
Palindrome Number - LeetCode
Can you solve this real interview question? Palindrome Number - 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. Ex
leetcode.com
수가 정수로 주어질 때 가장 간단하게 생각할 수 있는 방법은 string 형태로 변환한 뒤 [::-1] 을 통해 역순 정렬후 비교하는 것이다.
이 때 x 가 0보다 작으면 회문일 수 없으니 예외처리를 해주는 것이 좋다.
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
return str(x) == str(x)[::-1]
두번째 방법은 정수상태 그대로 활용하는 것이다.
이 때, x를 완전히 역순으로 정렬 후 확인하는 방법(1) 과 절반까지 확인하는 방법(2) 두가지가 있다.
(1)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
res = 0
org = x
while x > 0:
res = x%10 + res*10
x = x//10
return org == res
(2)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0 or (x>0 and x%10 == 0):
return False
res = 0
while x > res:
res = x%10 + res*10
x = x//10
return x == res or x == res//10
두번째 방법의 경우 10, 100등의 경우에 문제를 해결할 수 없기 때문에 예외처리를 해주어야 한다.
반응형