Palindrome Number

Table of contents
  1. Problem
  2. Explanation
  3. Solution

Problem

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

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
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.
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Explanation

Things to note:

  • Negative numbers are not palindromes.
  • First half of the digits must be the same as the reversed second half of the digits.

Let $n$ be the number of digits in $x$.

The first half of the digits can be obtained by dividing $x$ by $10^{n/2}$.

When $n$ is odd, however, the middle digit does not matter, so we should divide $x$ by $10^{(n+1)/2}$ instead.

\[\texttt{121 / 10^(4/2) = 1}\]

Then reverse sum the second half and compare it with the first half.


Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static boolean isPalindrome(int x) {
  if (x < 0) return false;

  // Calculate the number of digits in x
  int n = 0;
  int xx = x;
  while (xx > 0) {
    n++;
    xx /= 10;
  }

  int halfN = n / 2;
  int front = x / (int) Math.pow(10, (n % 2) == 0 ? halfN : halfN + 1);

  int backSum = 0;
  xx = x;
  for (int i = 0; i < halfN; i++) {
    backSum = backSum * 10 + xx % 10;
    xx /= 10;
  }

  return front == backSum;
}