Tutorialspoint
Problem
Solution
Submissions

Check if Number is Palindrome

Certification: Basic Level Accuracy: 83.33% Submissions: 6 Points: 5

Write a Java program to determine whether an integer is a palindrome. Do not convert the integer to a string — solve it mathematically.

Example 1
  • Input: x = 121
  • Output: true
  • Explanation:
    • Reverses to same value → it is a palindrome
Example 2
  • Input: x = -121
  • Output: false
  • Explanation:
    • Negative values are not palindromes
Constraints
  • -2^31 ≤ x ≤ 2^31 - 1
  • Do not convert to string
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
NumberSnowflakeTutorix
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

  • Negative numbers are not palindromes due to the minus sign.
  • Reverse the integer by extracting digits from right to left.
  • Be careful about integer overflow when reversing.
  • Compare the reversed integer with the original.
  • Handle edge cases like numbers ending with 0.

Steps to solve by this approach:

 Step 1: Handle edge cases - check if the number is negative (not a palindrome).

 Step 2: Check if the number ends with 0 and is not 0 itself (not a palindrome).
 Step 3: Initialize a variable to store the reversed number.
 Step 4: Extract digits from the original number one by one from right to left.
 Step 5: Build the reversed number by adding each digit and multiplying the previous sum by 10.
 Step 6: After reversing the entire number, compare it with the original number.
 Step 7: Return true if they are equal, false otherwise.

Submitted Code :