코딩테스트/리트코드
[리트코드 / LeetCode] 9. Palindrome Number 풀이 - python3
LEDPEAR
2021. 1. 1. 20:16
반응형
문제 원문
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
Example 1:
Input: x = 121 Output: true
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.
Example 4:
Input: x = -101 Output: false
Constraints:
-2³¹ <= x <= 2³¹ - 1
코드 원문
class Solution:
def isPalindrome(self, x: int) -> bool:
풀이
거꾸로 봐도 똑같은 숫자인지 판단하는 문제입니다.
음수는 -까지 문자로 인식해서 자연스래 양수만 True로 반환됩니다
간단하게 문자열을 뒤집는 함수를 작성하여 풀었습니다.
성공 코드
class Solution:
def reverse(text): //입력받은 문자열을 뒤집어서 반환
result = ""
for i in text :
result = i + result
return result
def isPalindrome(self, x: int) -> bool:
Num = str(x)
ReverseNum = Solution.reverse(Num)
return Num == ReverseNum
결과
Runtime: 72 ms, faster than 32.99% of Python3 online submissions for Palindrome Number.
Memory Usage: 14.2 MB, less than 70.28% of Python3 online submissions for Palindrome Number.
반응형