Palindrome Check in C++

Palindrome in C++: reverse the digits and compare. 121 is. 10 is not (reverse is 1).

BeginnerLoop ProgramsExample 7 of 14
palindrome-check.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int num, reversed = 0, remainder, original;
6
7 cout << "Enter a number: ";
8 cin >> num;
9
10 original = num;
11
12 // Reverse the number
13 while (num != 0) {
14 remainder = num % 10;
15 reversed = reversed * 10 + remainder;
16 num /= 10;
17 }
18
19 if (original == reversed) {
20 cout << original << " is a palindrome" << endl;
21 } else {
22 cout << original << " is not a palindrome" << endl;
23 }
24
25 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:

rem 1, reversed 1, num 12
rem 2, reversed 12, num 1
rem 1, reversed 121, num 0

if (original == reversed)

121 == 121 → 121 is a palindrome.

123:

rem 3, reversed 3, num 12
rem 2, reversed 32, num 1
rem 1, reversed 321, num 0
123 != 321 → not a palindrome

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.