# 9. Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

# Solution

Approach 1: Compare the number with its reverse.

Approach 2: Reverse the last half of the number and see if it's equal to the first half of the number.

Approach 3: Starting from both the head and tail of the number, compare each pair of digits towards each other.

# Code (Python)

# Code (C++)

Approach 1:

class Solution {
public:
    bool isPalindrome(int x) {
        int xCopy = x;
        long xReversed = 0;
        while (xCopy > 0)
        {
            xReversed = xReversed * 10 + xCopy % 10;
            xCopy /= 10;
        }
        return x == xReversed;
    }
};

Approach 2:

class Solution {
public:
    bool isPalindrome(int x) {
        // Special case for this approach:
        // need to check if the last digit is 0 (e.g., 12210).
        if (x < 0 || (x % 10 == 0 && x != 0))
            return false;
        int x1stHalf = x;
        int x2ndHalfReversed = 0;
        while (x1stHalf > x2ndHalfReversed)
        {
            x2ndHalfReversed = x2ndHalfReversed * 10 + x1stHalf % 10;
            x1stHalf /= 10;
        }
        return (x1stHalf == x2ndHalfReversed ||
                x1stHalf == x2ndHalfReversed / 10);
    }
};

Approach 3:

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int magnitude = 1;
        while (x / 10 >= magnitude)
        { // Avoid "x >= magnitude * 10" in case of overflow.
            magnitude *= 10;
        }
        while (magnitude > 1)
        {
            int head = (x / magnitude) % 10;
            int tail = x % 10;
            if (head != tail)
                return false;
            x /= 10;
            magnitude /= 100;
        }
        return true;
    }
};