Palindrome Number | Leetcode #9 | Easy

Rishikesh Dhokare
2 min readOct 18, 2020

In this post I will discuss the solution to another famous leetcode problem — Palindrome Number.

Problem:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

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

Example 1:

Input: x = 121
Output: true

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.

Example 4:

Input: x = -101
Output: false

Constraints:

  • -231 <= x <= 231 - 1

Solution:

In one of the previous posts, I discussed the solution to reverse an integer. Solution for this problem can be built on top of that code. Basically, we can reverse the number and compare both the original and reversed numbers. If they are equal, they are palindromes. If the number is negative, the reversed number can not be palindrome and this can be added as a initial condition to return false.

public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int reversed = reverse(x);
return x == reversed;
}

private int reverse(int x) {
long output = 0;
int currentDigit;
while (x != 0) {
currentDigit = x % 10;
x = x / 10;
output = output * 10 + currentDigit;
if (output > Integer.MAX_VALUE || output < Integer.MIN_VALUE) {
return 0;
}
}
return (int) output;
}

Hope this helps! Happy coding! 🙂

If you think the solution can be improved or misses something, feel free to comment. There is always some room for improvement.

Find the solutions to the leetcode problems here — https://github.com/rishikeshdhokare/leetcode-problems

--

--

Rishikesh Dhokare

I am a Software Engineer from India and working in Berlin, Germany. I write about technology, my experiences in Germany, travel in Europe.