What Is a Palindrome?

Definition: A palindrome is a number or string that reads the same forwards and backwards.

Examples:

Two Main Approaches to Check for a Palindrome

Approach A: Converting to a String

public boolean isPalindrome(int x) {
    if (x < 0) {
        return false;
    }
    var xStr = String.valueOf(x);

    // The contentEquals result is true if and only if this String represents 
    // the same sequence of char values as the specified sequence.
    return xStr.contentEquals(new StringBuilder(xStr).reverse());
}

Let’s break down the operations and analyze the Big O complexity:

Overall Complexity

Even though $n$ is generally small (e.g., at most 10 or 11 for typical integer sizes), the theoretical complexity is linear with respect to the number of digits.


Approach B: Reversing the Number Mathematically

public boolean isPalindrome(int x) {
    if (x < 0) {
        return false;
    }
    int original = x;
    int reverse = 0;
    while (x != 0) {
        reverse = reverse * 10 + x % 10;
        x = x / 10;
    }
    return original == reverse;
}

Complexity

Edge Cases