Easy–medium · digits
Reverse a Number
Read a positive integer and print it backwards: 1234 becomes 4321. Combines the digit-chopping pattern with building a new number — and hides a trailing-zeros subtlety.
At a glanceRebuild N backwards with rev = rev * 10 + n % 10 while chopping n — trailing zeros disappear on their own, so 1200 reverses to 21, not 0021.
Problem
Input: one positive integer N (1 ≤ N ≤ 10⁹).
Output: the digits of N in reverse order (leading zeros disappear naturally: reverse of 1200 is 21).
Samples:
| Input | Output |
|---|---|
1234 | 4321 |
1200 | 21 |
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 — pop and push
Two moves per iteration: pop the last digit of n with n % 10, then push it onto the result: rev = rev * 10 + digit;, then n /= 10;. Trace 1234 on paper: rev goes 4 → 43 → 432 → 4321.
Hint 2 — why 1200 becomes 21
When the popped digit is 0, rev * 10 + 0 just extends rev — but at the end, 0021 as a number is simply 21. Integers don't store leading zeros; if you wanted them kept, you'd need text (a different problem).
Solution (try it first!)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
cout << rev << endl;
return 0;
}
Same skeleton as Count the Digits, one extra line. This pattern generalizes: palindrome-number checks, digit sums, "is this number lucky" — all reuse pop-and-push. Next: a formatting challenge in Star Pyramid.
Deep dive
Why this works
rev = rev * 10 + n % 10 is the exact inverse of peeling. Peel and build together are the complete toolkit for number-as-digits problems.
The cost
O(d) time, O(1) space — no array required.
Where it goes wrong
- 1200 becomes 21, not 0021: trailing zeros turn into leading zeros of an int and disappear.
- Reversing 1,000,000,009 overflows int. A 32-bit int cannot hold every reversed value even when the input fits.
Next step
Reuse the result to compare: Palindrome Number.
Two things to remember
- rev = rev * 10 + digit builds a number one digit at a time.
- Reversal can overflow even when the input does not.
🐞 This version fails — open it and try
Adds the digits instead of shifting them left
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int rev = 0;
while (n > 0) {
rev = rev + n % 10;
n /= 10;
}
cout << rev << endl;
return 0;
}