Palindrome Number Algorithm

The Palindrome Number Algorithm is a computational method used to determine whether a given integer is a palindrome or not. A palindrome is a number that reads the same forward and backward, such as 121 or 12321. The algorithm is quite straightforward and can be implemented in various programming languages. It generally involves reversing the digits of the given number and comparing the reversed number with the original one. If both the reversed and original numbers are the same, then it is a palindrome; otherwise, it is not. To implement the Palindrome Number Algorithm, one can either use an iterative or a recursive method. In the iterative approach, the given number is first stored in a temporary variable. Then, the last digit of the number is extracted by taking the modulus with 10, and this digit is added to the reversed number after multiplying it by the current position (e.g., units, tens, hundreds, etc.) of the digit. The original number is then divided by 10 to remove the last digit, and this process is repeated until the original number becomes zero. Finally, the reversed number is compared with the temporary variable holding the original number. On the other hand, the recursive approach involves creating a separate function that takes the original number, the reversed number (initially 0), and the remaining number (initially the same as the original number) as parameters. In each recursive call, the function extracts the last digit, adds it to the reversed number, and removes it from the remaining number. The recursion continues until the remaining number becomes zero, and then the reversed number is compared with the original number.
class Solution {
public:
    bool isPalindrome(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if (x < 0) return false;
        
        int base = 1;
        while (x / base >= 10) {
            base *= 10;
        }
        while (x) {
            if (x / base != x % 10)
                return false;
            x = (x % base) / 10;
            base /= 100;
        }
        return true;
    }
};

LANGUAGE:

DARK MODE: