Determine whether an integer is a palindrome. Do this without extra space.
实现代码:
public boolean isPalindrome02(int x) {
String num= Integer.toString(x);
if(num.length()>11 || num.charAt(0)=='-' ){
//负数或者超范围
return false;
}
int i=0,j=num.length()-1;
while(i<=j){
if( !(num.charAt(i++)==num.charAt(j--)) ){
return false;
}
}
return true;
}
另一种思路,也就是第一种解法,在网上看到的在这里也放上:
public boolean isPalindrome(int x) {
if (x < 0)
return false;
int d = 1; // divisor
while (x / d >= 10)
d *= 10;
while (x > 0) {
int q = x / d; // quotient
int r = x % 10; // remainder
if (q != r)
return false;
x = x % d / 10;
d /= 100;
}
return true;
}
代码非常简洁。思路就是用一个除数将数字不断的截取收尾,判断。