题意:
Determine whether an integer is a palindrome. Do this without extra space. (Easy)
分析:
自己考虑的方法是利用Reverse Integer,然后查看rev与x是否相等,注意负数和0的判断(这里WA了一次)
代码1:
class Solution {
private:
int reverse(int x) {
long long result = ;
while (x != ) {
int temp = x % ;
x /= ;
result = result * + temp;
if (result > 0x7FFFFFFF || result < -0x7FFFFFFF) {
return ;
}
}
return result;
}
public:
bool isPalindrome(int x) {
if (x < ) {
return false;
}
int rex = reverse(x);
if (rex == && x != ) { //溢出(不是因为等于0而得到rex = 0)
return false;
}
if (rex == x) {
return true;
}
return false;
}
};
查看讨论区,有只比较一半的解法,循环中的思路和reverse integer类似,更为简洁,实现如下;
代码2:
class Solution {
public:
bool isPalindrome(int x) {
if (x < || (x % == && x != ) ) {
return false;
}
int sum = ;
while (x > sum) {
int temp = x % ;
sum = sum * + temp;
x /= ;
}
if (x == sum || x == sum / ) {
return true;
}
return false;
}
};