how to check the number is palindrome or not
To check if a number is a palindrome in C++, you can follow these steps:
- Declare and initialize the variables: number, revNumber, and originalNumber.
number
: This variable will store the original number that you want to check.revNumber
: This variable will store the reverse of the original number.originalNumber
: This variable will store the original number to compare with the reverse.Read the number from the user.
Initialize
originalNumber
with the value ofnumber
.Use a while loop to reverse the number:
- Initialize
revNumber
as 0. - In each iteration, extract the last digit of the
number
using the modulo operator (%). - Multiply
revNumber
by 10 and add the extracted digit to it. - Divide the
number
by 10 to remove the last digit. Repeat the above three steps until the
number
becomes 0.Compare
originalNumber
withrevNumber
:- If they are equal, print that the number is a palindrome.
- If they are not equal, print that the number is not a palindrome.
Here is an example code snippet that implements the above steps:
#include <iostream>
int main() {
int number, revNumber = 0, originalNumber;
std::cout << "Enter a number: ";
std::cin >> number;
originalNumber = number;
while (number != 0) {
int digit = number % 10;
revNumber = revNumber * 10 + digit;
number /= 10;
}
if (originalNumber == revNumber) {
std::cout << "The number is a palindrome." << std::endl;
} else {
std::cout << "The number is not a palindrome." << std::endl;
}
return 0;
}
This code prompts the user to enter a number, reverses it, and then compares the reversed number with the original number to determine if it is a palindrome or not.