Skip to content

Link to Question

EASY

Palindrome Number

Given an integer x, return true if x is a palindrome, and false otherwise.

An integer is a palindrome when it reads the same backward as forward. For example, 121 is a palindrome while 123 is not.

Example

Input:

x = 121

Output:

true

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.


Constraints

  • -2³¹ ≤ x ≤ 2³¹ - 1

Solution: Reverse the Number

  • Time Complexity: O(log₁₀(n)), where n is the given number. We divide the number by 10 for each iteration.
  • Space Complexity: O(1), as only a constant amount of extra space is used.
C++
class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0)  return false;
        int reverse = 0, x_copy = x;
        while(x) {
            if (reverse > (INT_MAX - x % 10) / 10) return false;
            reverse = reverse * 10 + x % 10;
            x /= 10;
        }
        return x_copy == reverse;
    }
};