
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:

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;
}