Easy–medium · digits

Palindrome Number

A number is a palindrome if it reads the same backwards: 121 yes, 123 no. If you solved Reverse a Number, you already own the whole algorithm — this problem is about recognizing that.

At a glanceReverse the number and compare it with the original — equal means palindrome, otherwise not a palindrome, and no string conversion is needed.

Problem

Input: one positive integer N (1 ≤ N ≤ 10⁹).

Output: palindrome if N reads the same reversed, otherwise not a palindrome (exactly these words).

Samples:

InputOutput
121palindrome
10not a palindrome

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — one gotcha: the loop destroys its input

The reversal loop n /= 10s its way to zero. Compare against the original, so save it first: int orig = n;. Forgetting the copy is the bug on this problem.

Hint 2 — single-digit numbers

7 reversed is 7 — every one-digit number is automatically a palindrome, and the reverse-and-compare approach handles that with no special case. If your code needs if (n < 10), you've over-engineered something.

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int orig = n;
    int rev = 0;
    while (n > 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    if (rev == orig) cout << "palindrome" << endl;
    else cout << "not a palindrome" << endl;
    return 0;
}

That's the digit-chopping toolkit fully assembled: count, sum, reverse, and now compare. Notice the whole solution is two lines of new code on top of the previous problem — pattern reuse is the real lesson here. Next: shapes with Star Pyramid.

Deep dive

Why this works

Once you can reverse, a palindrome is just reverse-and-compare. Spotting the reuse is the lesson — not writing new code.

The cost

O(d) time; you can halve it by building from both ends and meeting in the middle.

Where it goes wrong

  • Negative numbers are never palindromes because of the minus sign, yet -121 reverses to -121 numerically. Decide the case before you code.
  • to_string would be the easy path in a real compiler, but this engine has no std::string — the numeric route is the one that runs here.

Next step

The same symmetry question on text: Reverse a String.

Two things to remember

  • A new problem is often an old one plus a comparison.
  • Handle negatives before the algorithm, not after.
🐞 This version fails — open it and try

Compares with n, but the loop already zeroed it

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int rev = 0, m = n;
    while (m > 0) {
        rev = rev * 10 + m % 10;
        m /= 10;
    }
    if (n == rev) cout << "yes" << endl;
    else cout << "no" << endl;
    return 0;
}