Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
Solution
public class Solution {
public boolean isPalindrome(int x){
if(x < 0) return false;
int numberDigit = 0;
int testNum = x;
while(testNum > 0){
numberDigit ++;
testNum /= 10;
}
int start = numberDigit - 1;
int end = 0;
while(start > end){
int temp1 = getDigit(x, start);
int temp3 = getDigit(x, end);
if(temp1 != temp3)
return false;
start --;
end ++;
}
return true;
}
public static int getDigit(int x, int index){
if(index == 0) return x % 10;
else{
return (int)(x /= Math.pow(10,index)) % 10;
}
}
public static void main(String[] args) {
Solution s = new Solution();
s.isPalindrome(1001);
}
}