9. Palindrome Number LeetCode Solution

In this guide we will provide 9. Palindrome Number LeetCode Solution with best time and space complexity. The solution to Palindrome Number problem is provided in various programming languages like C++, Java and python. This will be helpful for you if you are preparing for placements, hackathon, interviews or practice purposes. The solutions provided here are very easy to follow and with detailed explanations.

Table of Contents

9. Palindrome Number LeetCode Solution image

Problem Statement of Palindrome Number

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

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

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.

Constraints:

-231 <= x <= 231 – 1

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

Complexity Analysis

  • Time Complexity: O(\log x)
  • Space Complexity: O(1)

9. Palindrome Number LeetCode Solution in C++

class Solution {
 public:
  bool isPalindrome(int x) {
    if (x < 0)
      return false;

    long reversed = 0;
    int y = x;

    while (y > 0) {
      reversed = reversed * 10 + y % 10;
      y /= 10;
    }

    return reversed == x;
  }
};
/* code provided by PROGIEZ */

9. Palindrome Number LeetCode Solution in Java

class Solution {
  public boolean isPalindrome(int x) {
    if (x < 0)
      return false;

    long reversed = 0;
    int y = x;

    while (y > 0) {
      reversed = reversed * 10 + y % 10;
      y /= 10;
    }

    return reversed == x;
  }
}
// code provided by PROGIEZ

9. Palindrome Number LeetCode Solution in Python

class Solution:
  def isPalindrome(self, x: int) -> bool:
    if x < 0:
      return False

    rev = 0
    y = x

    while y:
      rev = rev * 10 + y % 10
      y //= 10

    return rev == x
#code by PROGIEZ

Additional Resources

See also  45. Jump Game II LeetCode Solution

Feel free to give suggestions! Contact Us