Hide sidebar

Palindrome Number

Math
EasyLeetCode #9
15 min

Problem Statement

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

Example

Example 1:

Input: x = 121

121121

The number is a palindrome.

Output: true

Explanation: 121 reads as 121 from left to right and from right to left.

Solution (Revert Half the Number)

The core idea is to revert the second half of the number and compare it with the first half. If they are the same, the number is a palindrome.

We can do this by repeatedly taking the last digit of the number and adding it to a new 'reverted' number. We stop when the original number is less than or equal to the reverted number.

Algorithm Steps

  • Handle edge cases: negative numbers are not palindromes. If the last digit is 0, the number must be 0 to be a palindrome.
  • Initialize a revertedNumber to 0.
  • Loop while the original number x is greater than revertedNumber.
  • In each iteration, get the last digit of x and append it to revertedNumber.
  • Remove the last digit from x.
  • After the loop, compare x and revertedNumber. If the number has an odd number of digits, the middle digit will be at the end of revertedNumber, so we can ignore it by doing revertedNumber / 10.

Remaining (x)

121

Reverted

0

Start with the original number and a reverted number of 0.
Palindrome Number Solution

class Solution:
    def isPalindrome(self, x: int) -> bool:
        num = x
        n = 0
        
        if x < 0:
            return False
        
        while x != 0:
            # Build number backwards, get last and mult by 10
            last = x % 10
            n = n * 10 + last
            x //= 10
            
        return n == num