# [leetcode] Palindrome Number

### Palindrome Number

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.

tag: math

9/25/2015 update

a neater approach

```//negative can not be palindrome
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
int len = 0;
int y = x;
while(y > 0){
len++;
y = y / 10;
}
while(x > 0){
int highestDigit = x / pow(10, len - 1);
int lowestDigit = x % 10;
if(highestDigit != lowestDigit) return false;
x -= highestDigit * pow(10, len - 1);
x = x / 10;
len -= 2;
}
return true;
}
};```

```class Solution {
public:
int numOfZeros = 0;
bool isPalindrome(int x) {
int length;
int leastDigit, highestDigit;

if(x < 0){//negative integer can not be palindrome
return false;
}
length = getNumLength(x);
if (length == 1){
return true;
}

while(x >= 10){
leastDigit = x % 10;
highestDigit = getHighestDigit(x);
if (leastDigit != highestDigit){
return false;
}
int length = getNumLength(x);
x -= highestDigit * pow(10, length - 1);
if(highestDigit != 0){
numOfZeros = length - getNumLength(x) - 1;
}
x /= 10;
}
if(x > 0 && numOfZeros > 0){
return false;
}
return true;
}
int getNumLength(int x){
int i = 1;
while(x / 10 > 0){
x /= 10;
i++;
}
return i;
}
int getHighestDigit(int x){
int length = getNumLength(x);
int i = 0;
if(numOfZeros > 0){
numOfZeros--;
return 0;
}
while(x >= 0){
x -= pow(10, length - 1);
i++;
}
i--;
return i;
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.