Problem Statement

You are given an integer n. You need to check whether the number is a palindrome number or not. Return true if it's a palindrome number, otherwise return false.

A palindrome number is a number which reads the same both left to right and right to left.

Examples

Example 1:

Input: n = 151
Output: true

Explanation: When read from left to right - 151
When read from right to left - 151
Example 2:

Input: n = 167
Output: false

Explanation: When read from left to right - 167
When read from right to left - 761

Approaches

1️⃣ Modulus & Division

To determine whether a number is a palindrome, we can reverse the digits of the number and compare the reversed number with the original number. If they are the same, the number is a palindrome.

Steps:

  1. Reverse the Number:
    • Reverse the digits of the number using the approach discussed in the previous section.
    • Compare the reversed number with the original number.
  2. Check for Palindrome:
    • If the reversed number is equal to the original number, return True (the number is a palindrome).
    • Otherwise, return False (the number is not a palindrome).

Code:

#include <iostream>

bool isPalindrome(int n) {
    int originalNumber = n;
    int reversedNumber = 0;
    
    while (n > 0) {
        int digit = n % 10;  // Extract the last digit
        reversedNumber = reversedNumber * 10 + digit;  // Add it to reversedNumber
        n = n / 10;  // Remove the last digit
    }
    
    // Check if the original number is equal to its reversed form
    return originalNumber == reversedNumber;
}

int main() {
    int n;
    std::cout << "Enter a number: ";
    std::cin >> n;

    if (isPalindrome(n)) {
        std::cout << "The number is a palindrome." << std::endl;
    } else {
        std::cout << "The number is not a palindrome." << std::endl;
    }

    return 0;
}

Complexity Analysis:

  • Time Complexity:O(log10(N)) – In every iteration, N is divided by 10 (equivalent to the number of digits in N.)
  • Space Complexity:O(1) – Using a couple of variables i.e., constant space.