Algorithm Day105 - Palindrome Number

🧩 Problem Description

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

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


💬 Examples

Example 1

1
2
Input: x = 121
Output: true

Example 2

1
2
3
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-.

Example 3

1
2
3
Input: x = 10
Output: false
Explanation: Reads 01 from right to left.

💡 Intuition

Reversing the whole integer risks overflow. Instead, reverse only the second half of the number and compare it with the first half.
Edge cases:

  • Negative numbers are not palindromes.
  • Numbers ending with 0 are not palindromes unless the number is 0.

Stop when the reversed half is >= remaining half.


🔢 Java Code (Reverse Half)

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int rev = 0;
while (x > rev) {
rev = rev * 10 + x % 10;
x /= 10;
}
return x == rev || x == rev / 10;
}
}

⏱ Complexity Analysis

  • Time: O(log₁₀ n) — number of digits.
  • Space: O(1) — constant extra space.

✍️ Summary

  • Avoid full reversal to prevent overflow; reverse half instead.
  • Handle negative numbers and trailing zeros explicitly.
  • Simple, O(1) space solution suitable for interview settings.