📅  最后修改于: 2023-12-03 14:45:02.105000             🧑  作者: Mango
Palindrome number, also known as a numerical palindrome, is a number that remains the same when its digits are reversed. For example, 121, 1221, and 12321 are all palindromes.
In C++, we can use a simple algorithm to check whether a given number is a palindrome or not. The algorithm is as follows:
Here is a code snippet that implements this algorithm:
#include <iostream>
using namespace std;
int main() {
int input_num, temp_num, reversed_num = 0, remainder;
cout << "Enter a number: ";
cin >> input_num;
temp_num = input_num;
while (temp_num > 0) {
remainder = temp_num % 10;
reversed_num = reversed_num * 10 + remainder;
temp_num /= 10;
}
if (input_num == reversed_num) {
cout << input_num << " is a palindrome number." << endl;
}
else {
cout << input_num << " is not a palindrome number." << endl;
}
return 0;
}
Let's go through the code step-by-step.
First, we declare three integer variables: input_num
, temp_num
, and reversed_num
. input_num
is the number that the user inputs. temp_num
is a temporary variable that we will use to reverse the digits of input_num
. reversed_num
will hold the reversed value of temp_num
.
Next, we prompt the user to input a number and store it in input_num
.
Then, we initialize temp_num
with the value of input_num
.
The algorithm to reverse the digits of a number involves repeatedly dividing the number by 10 and taking the remainder. For example, the remainder of 123 divided by 10 is 3. We take this remainder and append it to the end of the reversed number. Then, we divide the number by 10, discarding the remainder. We repeat this process until the original number has been reduced to 0.
Here's how we implement this algorithm in C++. We use a while
loop that runs as long as temp_num
is greater than 0. In each iteration of the loop, we take the remainder of temp_num
when divided by 10 and store it in remainder
. We then multiply reversed_num
by 10 and add remainder
to it. Finally, we divide temp_num
by 10 to discard the last digit.
After the loop completes, reversed_num
should hold the reversed value of temp_num
.
Finally, we compare input_num
with reversed_num
. If they are the same, we print a message indicating that input_num
is a palindrome number. Otherwise, we print a message indicating that input_num
is not a palindrome number.
And that's it! We've implemented a simple program to check whether a number is a palindrome or not. With some additional code, we could modify this program to check whether a string is a palindrome or not.