Friday, September 2, 2016

LeetCode Online Judge-9. 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.
Acturally, I used extra space when solving this problem. But this answer was accepted. And I went to see the discussions about this problem. It seems impossible to solve the problem without extra space.
However, it's quite easy to solve this problem without the limit of extra space. Maybe there will be a perfect answer without extra space. Why not think about it?
OK, here comes my solution with extra space.

//Java Program: Palindrome Number
public class Solution {
    public boolean isPalindrome(int x) {
        String s = ((Integer)x).toString();
        for(int i=0;i<s.length()/2;++i) {
         if (s.charAt(i)!=s.charAt(s.length()-1-i)) {
         return false;
         }
        }
        return true;
    }
}