2024-01-10|閱讀時間 ‧ 約 23 分鐘

[Leetcode] 9. Palindrome Number

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




分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.