这道题我之前有印象了,就是通过reverse integer的思路来判断
其实吧,可以触类旁通,凡事判断整个输入是不是palindrome的题,都可以用reverse的思路来做,如同 link list
public class Solution {
public boolean isPalindrome(int x) {
/* if(x==0) return true;
else if(x<0) return false;
else{
int len=getLen(x);
for(int i=1; i<=len/2; i++){
if(getDigit(x, i)!=getDigit(x, len+1-i)) return false; // I changed int len=getLen(x)/2, but did not change he getDigit(x, len+1-i), and spent some time debugging. Lesson learned: changing one thing could affect all the places using the previous statement. so not just searching locally, but globally. Or just keep it the previous way
}
// reaching to the middle, still no false, then it got to be true
return true;
}
}
public int getDigit(int x, int pos){
return (x/(int)Math.pow(10,(pos-1)))%10; // here why (int)??? double has different range than int
}
public int getLen(int x){
int len=0;
while(x!=0){
len++;
x/=10; // typo, I wrote: len/=10; you silly!
}
return len;
}
// this is too slow, since iterate more than once, getLen iterate, and then compare iterate, can you iterate just once?*/
// the above was written in beginning of Jan.17.
// 看了一个极为简单的reverse int的做法来处理这个问题,太巧妙了!!重现一下。。。1.29.17
if(x==0) return true;
if(x<0 || x%10==0) return false; // !!! 特殊情况就是 后面是有一串0的数。。。但是0就是true的,所以要提前判断。。这个很关键
int reverseHalf=0;
while(x>reverseHalf){
reverseHalf=10*reverseHalf + x%10;
x=x/10;
}
return (x==reverseHalf || x== reverseHalf/10);
}
}