Palindrome Number easy

Problem Statement

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. For example, 121 is a palindrome, while 123 is not.

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.

Steps

  1. Handle Negative Numbers: Negative numbers are not palindromes. Return false immediately if the input x is negative.

  2. Reverse the Number: We'll reverse the input number and compare it to the original. We can do this efficiently using the modulo operator (%) and integer division (/).

  3. Compare Original and Reversed: If the original number and the reversed number are equal, it's a palindrome; otherwise, it's not.

Explanation

The core idea is to efficiently reverse the integer and compare it with the original. Using modulo and integer division avoids the need to convert the number to a string, which can be less efficient for very large integers.

The modulo operator (%) gives us the last digit, and integer division removes the last digit. We iteratively build the reversed number until the original number becomes 0.

Code

function isPalindrome(x: number): boolean {
    // Handle negative numbers
    if (x < 0) {
        return false;
    }

    // Handle single-digit numbers (they are always palindromes)
    if (x < 10) {
        return true;
    }

    let reversed = 0;
    let original = x;

    while (x > 0) {
        // Extract the last digit
        const lastDigit = x % 10;

        // Build the reversed number
        reversed = reversed * 10 + lastDigit;

        // Remove the last digit from the original number
        x = Math.floor(x / 10);
    }

    // Compare original and reversed numbers
    return original === reversed;
}

Complexity

  • Time Complexity: O(log10n), where n is the input number. This is because the number of digits in a number is proportional to the logarithm (base 10) of the number. We iterate through the digits once.

  • Space Complexity: O(1). The algorithm uses a constant amount of extra space, regardless of the input size. We only store a few integer variables.