C++, without any extra variable defined, i.e. No extra space.


  • 0
    M
        bool isPalindrome(int x) {
            if (x < 0) return false;
            while (x > 0) {
                if (x % 10 != (int)(x / (int)pow(10, (int)log10(x)))) {
                    return false;
                }
                if (log10(x) >= 1) {
                    if (((x / (int)pow(10, (int)log10(x) - 1)) % 10) == 0) {
                        x += (int)pow(10, (int)log10(x) - 1);
                        x += 10;
                    }
                }
                x -= (x % 10) * pow(10, (int)log10(x));
                x /= 10;
            }
            return true;
        }
    

    This solution AC. And maybe there is something I missed.
    The idea is to remove the highest digit and the lowest digit if they are the same.
    Otherwise, the integer is not a palindrome.
    For example,

    1st round: 12321 
    2nd round: 232
    3rd round: 3
    4th round: 0 --> jump out of while loop, return true
    

    To deal with the case 100021, which will be reduced to 0002 == 2 in the second round,
    I add 1 to the highest digit in the next round, i.e. 0, and to the lowest digit in the next round, i.e. 2.
    Then, this integer becomes 110031 in the end of the first round, and then 1003 in the second round.
    Theoretically, a palindrome integer is still a palindrome integer after this process, vice versa.
    If there is anything missing, please give me some comments!


Log in to reply
 

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