題目描述
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
想法
- 想法一:把整數(shù)轉換成字符串然后從中心往兩邊依次判斷
- 想法二:把整數(shù)轉過來作郭,但是這會有一個問題就是反過來的數(shù)可能超過了int的范圍
- 想法三:把整數(shù)的后半部分轉過來翁狐,跟前半部分進行比較眶拉,那么這里就有一個問題就是如何判斷整數(shù)已經(jīng)到了一半,那就是從后面拿數(shù)拿出來的數(shù)比拿掉后的大了就已經(jīng)達到了一半
代碼
public boolean isPalindrome(int x) {
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber/10;
//可能是奇數(shù)也可能偶數(shù)
}