Determine whether an integer is a palindrome. Do this without extra space.
拿到这道题第一个思维就是去模仿reverse integer那道题的思路
把一个数翻转一次,然后和原数相比,如果相等就返回true,否则返回false
这种方法在判断越界的时候比较困难,因为翻转后完全有可能数出现越界的情况。
代码如下
public boolean isPalindrome(int x) {
if (x < 0)
return false;
int y = 0;
int copy = x;
while (copy > 0) {
y = y * 10 + copy % 10;
copy /= 10;
}
return x == y;
}
其实这道题还有一种更牛逼的思维方式,来自于Code_Ganker, 就是直接比较这个数的首尾是否相等。那么如何取首尾呢?
123454321这个数 如果这个数%10,那么很容易得到尾数是1,怎么得到首位数呢
我们发现只要用1*10*10*10...一直到9位数的时候,然后用123454321/100000000就能得到首位数1了
最难的就在于结束比较后怎么把123454321变成2345432呢?
方法就在于我首先把这个数减掉100000000,得到23454321,然后这个数/10就能得到2345432了
代码如下
public boolean isPalindrome(int x) {
if (x < 0)
return false;
int div = 1;
while (div <= x / 10)
div *= 10;
while (x > 0) {
if (x / div != x % 10)
return false;
x %= div;
x /= 10;
div /= 100;
}
return true;
}