C++ Program to Reverse a Number with Output and Explanation
% 10 and build the reversed number by multiplying the result by 10 and adding the digit. For example: while (num != 0) { reversed = reversed * 10 + num % 10; num /= 10; }.Examples
How to Think About It
% 10. Then add that digit to a new number that grows by shifting digits left (multiply by 10). Repeat until the original number is zero.Algorithm
Code
#include <iostream> using namespace std; int main() { int num, reversed = 0; cout << "Enter a number: "; cin >> num; int original = num; while (num != 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } cout << "Reversed number of " << original << " is " << reversed << endl; return 0; }
Dry Run
Let's trace the number 1234 through the code to see how it reverses.
Initial values
num = 1234, reversed = 0
First iteration
digit = 1234 % 10 = 4; reversed = 0 * 10 + 4 = 4; num = 1234 / 10 = 123
Second iteration
digit = 123 % 10 = 3; reversed = 4 * 10 + 3 = 43; num = 123 / 10 = 12
Third iteration
digit = 12 % 10 = 2; reversed = 43 * 10 + 2 = 432; num = 12 / 10 = 1
Fourth iteration
digit = 1 % 10 = 1; reversed = 432 * 10 + 1 = 4321; num = 1 / 10 = 0
Loop ends
num is 0, loop stops; reversed = 4321
| num | digit | reversed |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number, like peeling one digit off.
Step 2: Build reversed number
Multiply the current reversed number by 10 to shift digits left, then add the extracted digit.
Step 3: Remove last digit
Divide the original number by 10 to remove the last digit and prepare for the next loop iteration.
Alternative Approaches
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string num; cout << "Enter a number: "; cin >> num; reverse(num.begin(), num.end()); cout << "Reversed number is " << num << endl; return 0; }
#include <iostream> using namespace std; void reverseNumber(int num) { if (num == 0) return; cout << num % 10; reverseNumber(num / 10); } int main() { int num; cout << "Enter a number: "; cin >> num; cout << "Reversed number is "; if (num == 0) cout << 0; else reverseNumber(num); cout << endl; return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few integer variables are used, so space is constant, O(1).
Which Approach is Fastest?
The arithmetic loop method is fastest and uses least memory. String conversion is simpler but uses extra space. Recursion adds call stack overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(d) | O(1) | Efficient and memory-friendly |
| String conversion | O(d) | O(d) | Simple code, uses extra memory |
| Recursive printing | O(d) | O(d) | No extra storage but uses call stack |