Tutorialspoint
Problem
Solution
Submissions

Implement a Function to Check if a Number is a Palindrome

Certification: Intermediate Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a Python function that determines whether a given number is a palindrome. A palindrome is a number that reads the same forwards and backwards.

Example 1
  • Input: 12321
  • Output: True
  • Explanation:
    • Step 1: Take the input number 12321.
    • Step 2: Read the number from left to right: 12321.
    • Step 3: Read the number from right to left: 12321.
    • Step 4: Compare both readings and find they are identical.
    • Step 5: Return True as the result.
Example 2
  • Input: 12345
  • Output: False
  • Explanation:
    • Step 1: Take the input number 12345.
    • Step 2: Read the number from left to right: 12345.
    • Step 3: Read the number from right to left: 54321.
    • Step 4: Compare both readings and find they are different.
    • Step 5: Return False as the result.
Constraints
  • -10^9 ≤ n ≤ 10^9
  • Return True if the number is a palindrome, False otherwise
  • Time Complexity: O(d), where d is the number of digits
  • Space Complexity: O(d) or O(1) depending on the approach
StringsFunctions / MethodsCognizantCapgemini
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Convert the number to a string and compare with its reverse: str(n) == str(n)[::-1]
  • Use mathematical operations to reverse the number without string conversion
  • Handle negative numbers: they cannot be palindromes due to the negative sign
  • For non-string approach: extract digits and rebuild the number in reverse

Steps to solve by this approach:

 Step 1: Handle edge case: negative numbers cannot be palindromes

 Step 2: Convert the number to a string for easier manipulation
 Step 3: Create a reversed version of the string using slicing with [::-1]
 Step 4: Compare the original string with its reversed version
 Step 5: Return True if they are identical (palindrome)
 Step 6: Return False if they are different (not a palindrome)
 Step 7: Example: 12321 is a palindrome because "12321" == "12321"[::-1]

Submitted Code :