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
'💻 LEETCODE' 카테고리의 다른 글
[LEETCODE] 20. Valid Parentheses (0) | 2022.11.23 |
---|---|
[LEETCODE] 14. Longest Common Prefix (0) | 2022.11.22 |
[LEETCODE] 383. Ransom Note (0) | 2022.11.22 |
[LEETCODE] 876. Middle of The Linked List (0) | 2022.11.22 |
[LEETCODE] 1342. Number of Steps to Reduce a Number to Zero (0) | 2022.11.16 |
댓글