9. Palindrome Number

Dare2Solve

Dare2Solve

9. Palindrome Number
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Description

The problem is to determine if a given integer x is a palindrome. A palindrome is a number that reads the same backward as forward. For example, 121 is a palindrome, while 123 is not.

Intuition

To check if an integer is a palindrome, we can reverse its digits and compare the reversed number with the original number. If they are the same, the number is a palindrome; otherwise, it is not. Negative numbers are not palindromes since they have a negative sign at the beginning.

Approach

  1. Check if the number is negative. If it is, return False immediately since negative numbers cannot be palindromes.
  2. Initialize reverse to 0, which will hold the reversed number.
  3. Make a copy of the original number x for comparison later.
  4. Use a while loop to reverse the digits of x:
    • In each iteration, multiply reverse by 10 and add the last digit of x to reverse.
    • Remove the last digit from x by integer division by 10.
  5. After the loop, compare the reversed number with the original number copy.
  6. Return True if they are equal, indicating that the number is a palindrome; otherwise, return False.

Complexity

Time Complexity:

O(d), where d is the number of digits in x. Each digit is processed once during the reversal.

Space Complexity:

O(1), since we only use a few extra variables for the reversal and comparison.

Code

C++

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        reverse = 0
        xcopy = x
        while x > 0:
            reverse = (reverse * 10) + (x % 10)
            x //= 10
        return reverse == xcopy

Python

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        long reverse = 0;
        int xcopy = x;
        while (x > 0) {
            reverse = (reverse * 10) + (x % 10);
            x /= 10;
        }
        return reverse == xcopy;
    }
};

Java

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        int reverse = 0;
        int xcopy = x;
        while (x > 0) {
            reverse = (reverse * 10) + (x % 10);
            x /= 10;
        }
        return reverse == xcopy;
    }
}

JavaScript

var isPalindrome = function (x) {
    if (x < 0) {
        return false;
    }
    let reverse = 0;
    let xcopy = x;
    while (x > 0) {
        reverse = (reverse * 10) + (x % 10);
        x = Math.floor(x / 10);
    }
    return reverse === xcopy;
};