[Leetcode] 9. Palindrome Number

2024/01/10閱讀時間約 1 分鐘

題目 : 9. 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.

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.


1.


class Solution:
def isPalindrome(self, x: int) -> bool:

# 因為小於0的值會有負號,所以可以直接回傳false
if x < 0 :
return False
else:
# 將數字轉成字串就可以直接和倒反後的數字字串比對是不是一樣的字串
if str(x) == str(x)[::-1]:
return True
else:
return False




7會員
36內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容