Palindrome Number

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

Follow up: Could you solve it without converting the integer to a string?

Example 1:


Input: x = 121
Output: true

Example 2:


Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:


Input: x = -101
Output: false

Constraints:

  • -231 <= x <= 231 - 1

Solutions

🧠 Cpp

class Solution
{
public:
    bool isPalindrome(int x)
    {
        //negative is not palindrome
        if(x < 0)
            return false;
        if(x == 0)
            return true;
        //if last number is 0 it is not a polindrome
        if(x%10 == 0)
            return false;

        //O(1) space
        long reversed = 0;

        for(long mod = 10, div = 1;
            reversed < x;
            mod *= 10, div *= 10)
        {
            //put last character as first on reversed, and so on
            reversed = reversed*10 + (x%mod)/div;
        }

        return reversed == x;

        //STRING SOLUTION O(N) space
        /*
        string num = std::to_string(x);
        const size_t num_len = num.size();
        for(size_t i = 0; i < num_len/2; ++i)
            if(num[i] != num[num_len-1-i])
                return false;        
        return true;
        */
    }
};

Last updated