Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
2nd implementation:
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.
1st iteration:
class Solution {
public:
bool isPalindrome(int x) {
// always false for negative, e.g., -11
if (x < 0) {
return false;
}
// get number of digits
int digit = 0;
int y = x;
while (y != 0) {
y /=10;
digit++;
}
// get most signficant digit and least siginficant
// digit and compare
// update number by stripping out the msd and lsd
// loop till there is 0 or 1 digit left
for (; digit > 1; digit -= 2) {
int left = x/pow(10, digit-1);
int right = x%10;
if (left != right) {
return false;
}
x = (x-(left*pow(10,digit-1) + right))/10;
}
return true;
}
};
2nd implementation:
class Solution {
public:
bool isPalindrome(int x) {
// always false for negative, e.g., -11
if (x < 0) {
return false;
}
// get the divider for the most signficant digit
int div = 1;
while (x/div >= 10) {
div *= 10;
}
while (x>0) {
// get most signficant digit and least significant digit and compare
int msd = x/div;
int lsd = x%10;
if (msd != lsd) {
return false;
}
// we stripping msd and lsd
// update the value and msd's divider
x = x%div/10;
div /=100;
}
return true;
}
};