题目描述
在不使用额外的内存空间的条件下判断一个整数是否是回文
提示:
负整数可以是回文吗?(比如-1)
如果你在考虑将数字转化为字符串的话,请注意一下不能使用额外空间的限制
你可以将整数翻转。但是,如果你做过题目“Reverse Integer”,你会知道将整数翻转可能会出现溢出的情况,你怎么处理这个问题?
这道题有更具普遍性的解法。
public boolean isPalindrome (int x) {
//分别比较x的左边和右边的数字:不同,返回false;相同,则去掉左右两边的数字继续比较
if (x < 0) {
return false;
}
int div = 1;
while (x / div >= 10) {//如x=1221,则div=1000
div *= 10;
}
while (x > 0) {
int left = x / div; //取左边的数字
int right = x % 10;//取右边的数字
if (left != right) {
return false;
}
x = x % div / 10; //去掉左边和右边的数字,继续比较
div /= 100; //如x去掉左右两边的数字后,x=22,div=10
}
return true;
}