Monday, November 25, 2013

LeetCode Problem : Palindrome Number

Problem

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.

Code

int numDigits(int n){
    int count = 1;
    while(n/10 != 0 ){
        n = n/10;
        count *= 10;
    }
    return count;
}
bool isPalindrome(int x) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    if(x < 0)
        return false;
    int n1 = numDigits(x);
    int n2 = 1;
    while(n1 > n2){
        if(( x/n1 % 10 ) != ( x/n2 % 10 ))
            return false;
        n2 *= 10;n1 /= 10;
    }
    return true; 
}

No comments:

Post a Comment