題目說明:給你一個數字,要你判斷此數字是否為回文
Case 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Case 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.
Case 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
解題思路:最簡單的方式就是將數字轉換成字串並且將字串反轉比對即可。另一種方式就是使用迴圈,從個位數字乘上x的位數減一,十位數字乘上x的位數減二,以此類推...
附上程式碼和註解
Java
class Solution {
public boolean isPalindrome(int x) {
StringBuilder builder=new StringBuilder();//建立stringbuilder物件
String y=String.valueOf(x);//數字轉字串
builder.append(y);//加入字串
builder.reverse();//反轉
if(y.equals(builder.toString())&&x>=0){
return true;
}
return false;
}
}
Python
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False#只要x<0一定是錯的(因為反轉會多一個負號)
else:
n=x
digit=len(str(x))-1
s=0
while x>0:
s+=pow(10,digit)*(x%10)
x//=10
digit-=1
return s==n