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
%. Then, add that digit to a new number that grows by shifting digits left (multiplying by 10). Repeat until the original number is gone.Algorithm
Code
using System; class Program { static void Main() { int num = 1234, reversed = 0; while (num > 0) { int digit = num % 10; reversed = reversed * 10 + digit; num /= 10; } Console.WriteLine(reversed); } }
Dry Run
Let's trace reversing 1234 through the code
Initial values
num = 1234, reversed = 0
First loop iteration
digit = 1234 % 10 = 4; reversed = 0 * 10 + 4 = 4; num = 1234 / 10 = 123
Second loop iteration
digit = 123 % 10 = 3; reversed = 4 * 10 + 3 = 43; num = 123 / 10 = 12
Third loop iteration
digit = 12 % 10 = 2; reversed = 43 * 10 + 2 = 432; num = 12 / 10 = 1
Fourth loop iteration
digit = 1 % 10 = 1; reversed = 432 * 10 + 1 = 4321; num = 1 / 10 = 0
Loop ends
num = 0, 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 using integer division to remove the last digit and repeat.
Alternative Approaches
using System; class Program { static void Main() { int num = 1234; char[] arr = num.ToString().ToCharArray(); Array.Reverse(arr); int reversed = int.Parse(new string(arr)); Console.WriteLine(reversed); } }
using System; class Program { static int Reverse(int num, int rev = 0) { if (num == 0) return rev; return Reverse(num / 10, rev * 10 + num % 10); } static void Main() { int num = 1234; Console.WriteLine(Reverse(num)); } }
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.
Space Complexity
Only a few integer variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
The arithmetic loop method is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(d) | O(1) | Fastest and memory efficient |
| String conversion | O(d) | O(d) | Simple code, less efficient for large numbers |
| Recursive | O(d) | O(d) | Elegant but risks stack overflow |