top of page

9. Palindrome Number

















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


Note

  • Palindromes cannot start or end with a zero like 010,000 etc.

A palindrome is a sequence of characters (such as a string, number, or list) that reads the same forward and backward. In other words, when the characters of a palindrome are reversed, the resulting sequence remains unchanged.

For example, consider the following examples:

  • Strings: "level", "madam", "racecar" are all palindromic strings because they read the same forward and backward.

  • Numbers: 121, 12321, and 1234321 are palindromic numbers because they have the same digits when read from left to right or right to left.

  • Lists: [1, 2, 3, 2, 1], ["a", "b", "b", "a"], and ["apple", "banana", "banana", "apple"] are examples of palindromic lists where the elements remain the same when read in reverse order.

In general, to determine if a sequence is a palindrome, you compare it with its reverse. If the original sequence is equal to its reverse, then it is a palindrome. The comparison is done based on the position of the characters or elements within the sequence.

Palindromes are often used in various applications, including text processing, string manipulation, and algorithmic problem-solving.

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


Solution:

Python3

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x=str(x)
        return x==x[::-1]

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


class Solution:
    def isPalindrome(self, x: int) -> bool:
    # Handle negative numbers and numbers ending in 0 (excluding 0 itself)
        if x < 0 or (x != 0 and x % 10 == 0):
            return False
    
    # Reverse half of the number
        reversed_num = 0
        while x > reversed_num:
            reversed_num = (reversed_num * 10) + (x % 10)
            x //= 10
    
    # Check for odd-length or even-length palindrome
        return x == reversed_num or x == reversed_num // 10


3 views0 comments

Recent Posts

See All

留言


bottom of page