C++ Program to Reverse Number Using While Loop
num % 10, building the reversed number with rev = rev * 10 + digit, and reducing the original number with num /= 10 until it becomes zero.Examples
How to Think About It
%. Then, build the reversed number by shifting the current reversed number left (multiply by 10) and adding the peeled digit. Keep doing this until the original number is zero.Algorithm
Code
#include <iostream> using namespace std; int main() { int num, rev = 0; cout << "Enter a number: "; cin >> num; int temp = num; while (temp > 0) { int digit = temp % 10; rev = rev * 10 + digit; temp /= 10; } cout << "Reversed number: " << rev << endl; return 0; }
Dry Run
Let's trace reversing the number 1234 through the code.
Initial values
num = 1234, rev = 0, temp = 1234
First iteration
digit = 1234 % 10 = 4; rev = 0 * 10 + 4 = 4; temp = 1234 / 10 = 123
Second iteration
digit = 123 % 10 = 3; rev = 4 * 10 + 3 = 43; temp = 123 / 10 = 12
Third iteration
digit = 12 % 10 = 2; rev = 43 * 10 + 2 = 432; temp = 12 / 10 = 1
Fourth iteration
digit = 1 % 10 = 1; rev = 432 * 10 + 1 = 4321; temp = 1 / 10 = 0
Loop ends
temp is 0, reversed number is 4321
| temp | digit | rev |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using temp % 10 gets the last digit of the number.
Step 2: Build reversed number
Multiply current reversed number by 10 to shift digits left, then add the extracted digit.
Step 3: Remove last digit
Divide the number by 10 using temp /= 10 to discard the last digit.
Alternative Approaches
#include <iostream> using namespace std; int reverse(int num, int rev = 0) { if (num == 0) return rev; return reverse(num / 10, rev * 10 + num % 10); } int main() { int num; cout << "Enter a number: "; cin >> num; cout << "Reversed number: " << reverse(num) << endl; return 0; }
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string numStr; cout << "Enter a number: "; cin >> numStr; reverse(numStr.begin(), numStr.end()); cout << "Reversed number: " << numStr << endl; return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time complexity is O(d), where d is the number of digits.
Space Complexity
Only a few integer variables are used, so space complexity is O(1), constant space.
Which Approach is Fastest?
The while loop approach is fastest and most memory efficient compared to recursion or string conversion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(d) | O(1) | Efficient and simple for numeric reversal |
| Recursion | O(d) | O(d) | Elegant but uses call stack memory |
| String conversion | O(d) | O(d) | Simple code, less efficient for large numbers |