How to check a Palindrome Number by C++

Profile Picture

saxenadivya859

Sunday, 2024-08-04



To check if a number is a palindrome in C++, you can follow a similar approach as in C. However, C++ provides some additional features that can make the implementation cleaner and more robust. Here's a step-by-step guide along with a C++ example to help you understand how to achieve this:


Approach:


  1. Reverse the number: Extract digits from the original number and construct a new number by appending these digits in reverse order.
  2. Compare the original number with the reversed number: If they are the same, then the original number is a palindrome.


C++ Programming Language - GeeksforGeeks


Code:

cpp
Copy code
#include <iostream>

bool isPalindrome(int num) {
    int originalNum = num; // Store the original number
    int reversedNum = 0;  // Variable to store the reversed number
    int remainder;

    // Handle negative numbers as not being palindromes
    if (num < 0) {
        return false;
    }

    // Reverse the number
    while (num != 0) {
        remainder = num % 10;          // Get the last digit
        reversedNum = reversedNum * 10 + remainder; // Construct the reversed number
        num /= 10;                     // Remove the last digit from num
    }

    // Check if the original number is equal to the reversed number
    return originalNum == reversedNum;
}

int main() {
    int number;

    // Input number from user
    std::cout << "Enter an integer: ";
    std::cin >> number;

    // Check and output whether the number is a palindrome
    if (isPalindrome(number)) {
        std::cout << number << " is a palindrome." << std::endl;
    } else {
        std::cout << number << " is not a palindrome." << std::endl;
    }

    return 0;
}




How did you feel about this post?

😍 🙂 😐 😕 😡