Setting up a local array is accepted. Still not sure about the extra space.


  • 0
    K

    This is my accepted answer. There is an array, reverse[20] that was used without giving much thought about 'extra space' constraint. After becoming aware and searching through discussions, I am still not sure how 'extra space' constraint applies to.

    bool isPalindrome(int x) {
        // Palindrome is for 0 <= x
        // One digit integers are palindromes by definition
        if (x < 0) return false;
        else if (x < 10) return true;
    
        int count = 0;
        int reverse[20]; // should cover the 64bit case
        
        do {
            reverse[count++] = x % 10;
            x = x / 10;
        } while (x != 0);
        
        bool result = true;
        // comparing both halves are enough
        for (int i=0; i<count/2; ++i)
        {
            if (reverse[i] != reverse[count-1-i])
            {
                result = false;
                break;
            }
        }
        return result;
    }

  • 0
    G

    You don't need an extra space actually. You can use "int result" to store the reversed number, not array. for example,int temp = x; int result = 0; while(temp != 0) {result = result*10 + temp%10; temp /= 10;} After this, compare result and x to see if they are equal. If they are, return true. Or else return false.


  • 0
    G

    do not set up space such as arrays or strings. setting up varibles like int is OK.


  • 0
    N

    is the correct understanding for this constraint - "Do this without extra space"?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.