Palindrome Check in C++
Palindrome in C++: reverse the digits and compare. 121 is. 10 is not (reverse is 1).
1#include <iostream>2using namespace std;34int main() {5 int num, reversed = 0, remainder, original;67 cout << "Enter a number: ";8 cin >> num;910 original = num;1112 // Reverse the number13 while (num != 0) {14 remainder = num % 10;15 reversed = reversed * 10 + remainder;16 num /= 10;17 }1819 if (original == reversed) {20 cout << original << " is a palindrome" << endl;21 } else {22 cout << original << " is not a palindrome" << endl;23 }2425 return 0;26}
Output
Enter a number: 121 121 is a palindrome
What's going on
A palindrome number reads the same forwards and backwards. 121 is. 123 is not. This C++ program reverses the digits and compares.
That's the same loop as Reverse a Number. The extra pieces are original and the if.
int num, reversed = 0, remainder, original;
reversed starts at 0. original will hold the value cin just gave you, because the loop wipes num.
cin >> num;
original = num;
Sample: 121. Skip this copy and after the loop num is 0, so you compare 0 to 121 and always lose.
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
Walk 121:
if (original == reversed)
121 == 121 → 121 is a palindrome.
123:
Single digits (7) reverse to themselves. Always palindromes.
10 is the usual trap. Reverse as an int is 1, not 01. So 10 is not a palindrome. Trailing zeros in the original become leading zeros in the reverse, and integers drop those.
Don't reverse into a string unless the homework asks for it. For a number, % 10 / / 10 is the whole trick.