Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
更好的解法:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
public class Solution {
public boolean isPalindrome(int x) {
if(x < 0)
return false;
else if(x < 10)
return true;
int a[] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
int b[] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
double index = 0;
double number1 = x;
for(double i = 0;i < 13; i ++){
if(x >= Math.pow(10, i+1)){
a[(int) i] = (int) (number1 % 10);
index = i;
number1 = number1/10 ;
// System.out.println(number1);
}
else{
a[(int) i] = (int) number1;
break;
}
}
for(double i = 0;i <= index + 1; i ++)
b[(int) i] = (int) ((int)(x % Math.pow(10, index - i + 2))/Math.pow(10, index - i + 1));
int flag = 1;
for(int j = 0;j <= index + 2; j ++){
// System.out.println("This is the "+ j + "th"+ a[j] + " " + b[j]);
if(a[j] != b[j])
flag = 0;
}
if(flag == 0)
return false;
return true;
}
}
更好的解法:
public class Solution {
public boolean isPalindrome(int x) {
//negative numbers are not palindrome
if (x < 0)
return false;
// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int left = x / div;
int right = x % 10;
if (left != right)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
}