1,自己C++解法:
注意第一次错在哪里。。。
class Solution {
public:
bool isPalindrome(int x) {
string a;
if (x<0){
return false;
}
else if(x==0)return true;
while(x>0){//-----------不是x%10啊,,,,,,,,,,,,,,,,,,,,,,
a+=x%10;
x/=10;
}
int n=a.size();
int i=0,j=n-1;
while(i<=j){
if(a[i]!=a[j])
break;
i++;
j--;
}
if(i>j) return true;
else return false;
}
};
总结:上述其实可以不用string,,直接用int比较是否相等也可以,只要不超出INT_MAX和INT_MIN
2,官方解法:
public class Solution {
public bool IsPalindrome(int x) {
// Special cases:
// As discussed above, when x < 0, x is not a palindrome.
// Also if the last digit of the number is 0, in order to be a palindrome,
// the first digit of the number also needs to be 0.
// Only 0 satisfy this property.
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
// For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
// since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber || x == revertedNumber/10;
}
}
好处:只用了一半就来判定结果,当长度是奇数时需要return后面那个/10