要是面试遇到这道题,估计要挂了,想了很久才做出来。
因为不许使用多余的空间,所以一开始想的是两头缩小,比如12321->232->3,最后认为对称。结果遇到1021就失败了,02变成2,也认为两边对称。后来就想多了,觉得有什么特殊的算法,最后又回到这个想法,中间开始缩小。
虽然代码有点Ugly,很长,很容易出错,但值得欣慰的是完全按照要求来的,呵呵一下吧。
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x >= 1000000000) {
if (x / 100000 % 10 == x % 100000 / 10000) {
x = x % 10000 + x / 100000 * 10000;
return isPalindrome(x);
}
else {
return false;
}
}
else if (x >= 100000000) {
x = x % 10000 + x / 100000 * 10000;
return isPalindrome(x);
}
else if (x >= 10000000) {
if (x / 10000 % 10 == x % 10000 / 1000) {
x = x % 1000 + x / 100000 * 1000;
return isPalindrome(x);
}
else {
return false;
}
}
else if (x >= 1000000) {
x = x % 1000 + x / 10000 * 1000;
return isPalindrome(x);
}
else if (x >= 100000) {
if (x / 1000 % 10 == x % 1000 / 100) {
x = x % 100 + x / 10000 * 100;
return isPalindrome(x);
}
else {
return false;
}
}
else if (x >= 10000) {
x = x % 100 + x / 1000 * 100;
return isPalindrome(x);
}
else if (x >= 1000) {
if (x / 100 % 10 == x % 100 / 10) {
x = x % 10 + x / 1000 * 10;
return isPalindrome(x);
}
else {
return false;
}
}
else if (x >= 100) {
x = x % 10 + x / 100 * 10;
return isPalindrome(x);
}
else if (x >= 10) {
if (x / 10 == x % 10) {
return true;
}
else {
return false;
}
}
else {
return true;
}
}
};